file_controller.js 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  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. useSpreadMoveFile: true,
  234. };
  235. const allFiling = await ctx.service.filing.getValidFiling(ctx.params.id, 'all');
  236. const canManageDir = this.hasFilePermission(ctx, 'manage_dir');
  237. renderData.categoryData = await ctx.service.category.getAllCategory(ctx.subProject);
  238. renderData.filingPermissionMap = await ctx.service.subProjectFilingPermission.getPermissionMap(
  239. ctx.subProject.id,
  240. ctx.session.sessionUser.accountId,
  241. allFiling,
  242. ctx.subProject.permission.filing_type,
  243. ctx.subProject.permission.file_permission,
  244. this.isAdmin(ctx)
  245. );
  246. this.applyFileConfigViewPermission(ctx, renderData.filingPermissionMap);
  247. renderData.filing = this.filterVisibleFiling(allFiling, renderData.filingPermissionMap);
  248. // 共用 file_modal.ejs 需要渲染全部弹窗,实际显示与操作由 filingPermissionMap 控制。
  249. renderData.canFiling = true;
  250. renderData.canUpload = true;
  251. renderData.canEdit = false;
  252. renderData.canManageDir = this.hasFileConfigPermission(ctx);
  253. renderData.needFilingInitialization = canManageDir && allFiling.length === 0;
  254. renderData.filingInitializationTemplates = [];
  255. renderData.filingInitializationProjects = [];
  256. if (renderData.needFilingInitialization) {
  257. renderData.filingInitializationTemplates = await ctx.service.filingTemplateList.getAllDataByCondition({
  258. columns: ['id', 'name'],
  259. where: { ft_type: ctx.service.filingTemplateList.FtType.org },
  260. orders: [['create_time', 'asc']],
  261. });
  262. renderData.filingInitializationProjects = await ctx.service.subProject.getManageDirProjects(
  263. ctx.session.sessionProject.id,
  264. ctx.session.sessionUser.accountId,
  265. this.isAdmin(ctx),
  266. ctx.subProject.id
  267. );
  268. }
  269. renderData.fileReferenceList = await ctx.service.subProject.getFileReference(ctx.subProject, ctx.service.subProject.FileReferenceType.file);
  270. await this.layout('file/filesjs.ejs', renderData, 'file/file_modal.ejs');
  271. } catch (err) {
  272. ctx.log(err);
  273. }
  274. }
  275. async initializeFiling(ctx) {
  276. try {
  277. this.checkFilePermission(ctx, 'manage_dir');
  278. const data = JSON.parse(ctx.request.body.data);
  279. if (!data || !data.init_type) throw '请选择初始化方式';
  280. let sourceData = [];
  281. let templateData = null;
  282. if (data.init_type === 'template') {
  283. if (!data.template_id) throw '请选择系统模板库';
  284. templateData = await ctx.service.filingTemplateList.getDataByCondition({
  285. id: data.template_id,
  286. ft_type: ctx.service.filingTemplateList.FtType.org,
  287. });
  288. if (!templateData) throw '选择的系统模板不存在';
  289. sourceData = await ctx.service.filingTemplate.getAllDataByCondition({
  290. where: { temp_id: templateData.id },
  291. orders: [['tree_level', 'asc'], ['tree_order', 'asc']],
  292. });
  293. if (sourceData.length === 0) throw '选择的系统模板没有目录数据';
  294. } else if (data.init_type === 'project') {
  295. if (!data.source_spid) throw '请选择来源项目';
  296. const sourceProjects = await ctx.service.subProject.getManageDirProjects(
  297. ctx.session.sessionProject.id,
  298. ctx.session.sessionUser.accountId,
  299. this.isAdmin(ctx),
  300. ctx.subProject.id
  301. );
  302. const sourceProject = sourceProjects.find(project => {
  303. return String(project.id) === String(data.source_spid);
  304. });
  305. if (!sourceProject) throw '来源项目不存在或您没有管理目录权限';
  306. sourceData = await ctx.service.filing.getValidFiling(sourceProject.id, 'all');
  307. }
  308. const result = await ctx.service.filing.initializeDirectory(
  309. ctx.subProject.id,
  310. data.init_type,
  311. sourceData,
  312. ctx.session.sessionUser.accountId,
  313. templateData
  314. );
  315. ctx.body = { err: 0, msg: '', data: result };
  316. } catch (err) {
  317. ctx.log(err);
  318. ctx.ajaxErrorBody(err, '初始化资料目录失败');
  319. }
  320. }
  321. async configDir(ctx) {
  322. try {
  323. const canManageDir = this.hasFilePermission(ctx, 'manage_dir');
  324. const canAuthUser = this.hasFilePermission(ctx, 'auth_user');
  325. if (!canManageDir && !canAuthUser) throw '您无权查看配置目录';
  326. const renderData = {
  327. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.config_dir),
  328. };
  329. renderData.canManageDir = canManageDir;
  330. renderData.canAuthUser = canAuthUser;
  331. renderData.filing = await ctx.service.filing.getValidFiling(ctx.params.id, 'all');
  332. await this.fillFilingAddUserNames(ctx, renderData.filing);
  333. renderData.permissionData = renderData.canAuthUser ? await ctx.service.subProjPermission.getPermission(ctx.params.id) : [];
  334. renderData.filingPermissionData = renderData.canAuthUser
  335. ? await ctx.service.subProjectFilingPermission.getConfigPermissionRows(ctx.params.id, renderData.filing) : [];
  336. if (renderData.canAuthUser) {
  337. await this.fillFilingPermissionCreatorNames(
  338. ctx, renderData.filing, renderData.filingPermissionData
  339. );
  340. }
  341. renderData.accountList = renderData.canAuthUser
  342. ? await ctx.service.subProjDataRange.getSelectableAccounts(ctx.subProject, 'file') : [];
  343. await this.layout('file/config_dir.ejs', renderData);
  344. } catch (err) {
  345. ctx.log(err);
  346. ctx.session.postError = err.toString();
  347. ctx.redirect(this.menu.menu.dashboard.url);
  348. }
  349. }
  350. async configDirLock(ctx) {
  351. const redirectUrl = `/sp/${ctx.subProject.id}/config-dir`;
  352. try {
  353. this.checkFilePermission(ctx, 'manage_dir');
  354. const lock = Number(ctx.request.body.lock);
  355. if (lock !== 0 && lock !== 1) throw '锁定状态参数错误';
  356. await ctx.service.subProject.save({ id: ctx.subProject.id, lock_file: lock });
  357. ctx.redirect(redirectUrl);
  358. } catch (err) {
  359. ctx.log(err);
  360. ctx.postError(err, '资料管理锁定状态修改失败');
  361. ctx.redirect(redirectUrl);
  362. }
  363. }
  364. async configDirUpdate(ctx) {
  365. try {
  366. this.checkFilePermission(ctx, 'manage_dir');
  367. this.checkLock(ctx);
  368. const data = JSON.parse(ctx.request.body.data);
  369. const result = await this.updateFiling(ctx, data);
  370. if (result && result.create) await this.fillFilingAddUserNames(ctx, result.create);
  371. ctx.body = { err: 0, msg: '', data: result };
  372. } catch (err) {
  373. ctx.log(err);
  374. ctx.ajaxErrorBody(err, '修改失败');
  375. }
  376. }
  377. async configDirMoveFiles(ctx) {
  378. try {
  379. this.checkFilePermission(ctx, 'manage_dir');
  380. this.checkLock(ctx);
  381. const data = JSON.parse(ctx.request.body.data);
  382. if (!data.source_filing_id || !data.target_filing_id) throw '缺少参数';
  383. const sourceFiling = await this.getProjectFiling(ctx, data.source_filing_id);
  384. const targetFiling = await this.getProjectFiling(ctx, data.target_filing_id);
  385. const result = await ctx.service.file.moveFilingFiles(sourceFiling, targetFiling);
  386. ctx.body = { err: 0, msg: '', data: result };
  387. } catch (err) {
  388. ctx.log(err);
  389. ctx.ajaxErrorBody(err, '批量移动文件失败');
  390. }
  391. }
  392. async getFilingNodePermission(ctx) {
  393. try {
  394. this.checkFilePermission(ctx, 'auth_user');
  395. const filingId = ctx.request.body.filing_id;
  396. const filing = await this.getProjectFiling(ctx, filingId);
  397. const selectableAccounts = await ctx.service.subProjDataRange.getSelectableAccounts(ctx.subProject, 'file');
  398. const projectAccounts = await ctx.service.subProjPermission.getPermission(ctx.subProject.id);
  399. const permissionRows = await ctx.service.subProjectFilingPermission.getConfigPermissionRows(
  400. ctx.subProject.id, [filing]
  401. );
  402. const authorizedIds = permissionRows.filter(row => {
  403. return String(row.filing_id || '') === String(filing.id);
  404. }).map(row => Number(row.uid));
  405. const accountMap = {};
  406. projectAccounts.forEach(permission => {
  407. const userId = Number(permission.uid);
  408. accountMap[userId] = {
  409. id: userId,
  410. name: permission.name,
  411. company: permission.company,
  412. role: permission.role,
  413. };
  414. });
  415. selectableAccounts.forEach(account => {
  416. accountMap[Number(account.id)] = account;
  417. });
  418. const authorizedUsers = authorizedIds.map(uid => accountMap[uid]).filter(Boolean).map(account => {
  419. return {
  420. id: Number(account.id),
  421. name: account.name,
  422. company: account.company,
  423. role: account.role,
  424. };
  425. }).filter((account, index, list) => {
  426. return list.findIndex(item => Number(item.id) === Number(account.id)) === index;
  427. });
  428. /*
  429. * 下拉选择仍只使用数据范围内账号;这里额外合并项目账号,
  430. * 是为了让已经存在的旧授权不会因数据范围调整而从弹窗消失。
  431. */
  432. const selectableIds = selectableAccounts.map(account => Number(account.id));
  433. authorizedUsers.forEach(account => {
  434. account.selectable = selectableIds.indexOf(Number(account.id)) >= 0;
  435. });
  436. ctx.body = { err: 0, msg: '', data: authorizedUsers };
  437. } catch (err) {
  438. ctx.log(err);
  439. ctx.ajaxErrorBody(err, '获取授权用户失败');
  440. }
  441. }
  442. async saveFilingNodePermission(ctx) {
  443. try {
  444. this.checkFilePermission(ctx, 'auth_user');
  445. this.checkLock(ctx);
  446. const data = JSON.parse(ctx.request.body.data);
  447. if (!data || !data.filing_id) throw '请选择需要授权的资料目录';
  448. if (!(data.user_permissions instanceof Array)) throw '授权用户权限格式错误';
  449. if (data.user_permissions.find(x => !x || typeof x !== 'object')) throw '授权用户权限格式错误';
  450. const filing = await this.getProjectFiling(ctx, data.filing_id);
  451. const userPermissions = data.user_permissions;
  452. const requestedUserIds = userPermissions.map(x => Number(x.uid !== undefined ? x.uid : x.id));
  453. if (requestedUserIds.find(uid => !Number.isInteger(uid) || uid <= 0)) throw '授权用户数据错误';
  454. if (new Set(requestedUserIds).size !== requestedUserIds.length) throw '授权用户数据重复';
  455. const selectableAccounts = await ctx.service.subProjDataRange.getSelectableAccounts(ctx.subProject, 'file');
  456. const selectableIds = selectableAccounts.map(account => Number(account.id));
  457. const currentPermissionRows = await ctx.service.subProjectFilingPermission.getConfigPermissionRows(
  458. ctx.subProject.id, [filing]
  459. );
  460. const currentUserIds = currentPermissionRows.filter(row => {
  461. return String(row.filing_id || '') === String(filing.id);
  462. }).map(row => Number(row.uid));
  463. const invalidUserId = requestedUserIds.find(uid => {
  464. return selectableIds.indexOf(uid) < 0 && currentUserIds.indexOf(uid) < 0;
  465. });
  466. if (invalidUserId) throw '选择的用户超出资料管理数据范围';
  467. await ctx.service.subProjectFilingPermission.savePermissions(
  468. ctx.subProject,
  469. filing,
  470. userPermissions,
  471. ctx.session.sessionUser.accountId,
  472. { replaceExisting: true }
  473. );
  474. const savedPermissionRows = await ctx.service.subProjectFilingPermission.getRows(ctx.subProject.id);
  475. const savedPermissions = await ctx.service.subProjectFilingPermission.getConfigPermissionRows(
  476. ctx.subProject.id, [filing]
  477. );
  478. await this.fillFilingAddUserNames(ctx, [filing]);
  479. await this.fillFilingPermissionCreatorNames(ctx, [filing], savedPermissionRows);
  480. ctx.body = {
  481. err: 0,
  482. msg: '',
  483. data: {
  484. permissions: savedPermissions,
  485. filings: [{ id: filing.id, add_user: filing.add_user || '' }],
  486. },
  487. };
  488. } catch (err) {
  489. ctx.log(err);
  490. ctx.ajaxErrorBody(err, '保存授权用户失败');
  491. }
  492. }
  493. async addFilingNodePermissions(ctx) {
  494. await this._saveBatchFilingNodePermissions(ctx, false);
  495. }
  496. async coverFilingNodePermissions(ctx) {
  497. await this._saveBatchFilingNodePermissions(ctx, true);
  498. }
  499. async _saveBatchFilingNodePermissions(ctx, replaceExisting) {
  500. try {
  501. this.checkFilePermission(ctx, 'auth_user');
  502. this.checkLock(ctx);
  503. const data = JSON.parse(ctx.request.body.data);
  504. if (!data) throw '批量授权数据错误';
  505. if (!(data.target_filing_ids instanceof Array) || data.target_filing_ids.length === 0) {
  506. throw '请选择目标资料目录';
  507. }
  508. if (data.target_filing_ids.length > 500) throw '一次最多选择500个目标资料目录';
  509. if (!(data.user_permissions instanceof Array) || data.user_permissions.length === 0) {
  510. throw '请选择需要配置的授权用户';
  511. }
  512. if (data.user_permissions.find(x => !x || typeof x !== 'object')) {
  513. throw '授权用户权限格式错误';
  514. }
  515. const targetFilingIds = data.target_filing_ids.map(id => String(id || '').trim());
  516. if (targetFilingIds.find(id => !id)) throw '目标资料目录数据错误';
  517. if (new Set(targetFilingIds).size !== targetFilingIds.length) throw '目标资料目录重复';
  518. const targetFilingRows = await ctx.service.filing.getAllDataByCondition({
  519. where: {
  520. id: targetFilingIds,
  521. spid: ctx.subProject.id,
  522. is_deleted: 0,
  523. },
  524. });
  525. const targetFilingMap = {};
  526. targetFilingRows.forEach(filing => { targetFilingMap[String(filing.id)] = filing; });
  527. if (targetFilingIds.find(filingId => !targetFilingMap[filingId])) throw '目标资料目录不存在';
  528. const targetFilings = targetFilingIds.map(filingId => targetFilingMap[filingId]);
  529. const userPermissions = data.user_permissions;
  530. const requestedUserIds = userPermissions.map(x => Number(x.uid !== undefined ? x.uid : x.id));
  531. if (requestedUserIds.find(uid => !Number.isInteger(uid) || uid <= 0)) throw '授权用户数据错误';
  532. if (new Set(requestedUserIds).size !== requestedUserIds.length) throw '授权用户数据重复';
  533. const selectableAccounts = await ctx.service.subProjDataRange.getSelectableAccounts(ctx.subProject, 'file');
  534. const selectableIds = selectableAccounts.map(account => Number(account.id));
  535. const invalidUserId = requestedUserIds.find(uid => selectableIds.indexOf(uid) < 0);
  536. if (invalidUserId) throw '选择的用户超出资料管理数据范围';
  537. const permissionService = ctx.service.subProjectFilingPermission;
  538. if (replaceExisting) {
  539. await permissionService.coverPermissionsToFilings(
  540. ctx.subProject,
  541. targetFilings,
  542. userPermissions,
  543. ctx.session.sessionUser.accountId
  544. );
  545. } else {
  546. await permissionService.addPermissionsToFilings(
  547. ctx.subProject,
  548. targetFilings,
  549. userPermissions,
  550. ctx.session.sessionUser.accountId
  551. );
  552. }
  553. const savedPermissionRows = await ctx.service.subProjectFilingPermission.getRows(ctx.subProject.id);
  554. const targetPermissionRows = await ctx.service.subProjectFilingPermission.getConfigPermissionRows(
  555. ctx.subProject.id, targetFilings
  556. );
  557. await this.fillFilingAddUserNames(ctx, targetFilings);
  558. await this.fillFilingPermissionCreatorNames(ctx, targetFilings, savedPermissionRows);
  559. ctx.body = {
  560. err: 0,
  561. msg: '',
  562. data: {
  563. permissions: targetPermissionRows,
  564. filings: targetFilings.map(filing => ({
  565. id: filing.id,
  566. add_user: filing.add_user || '',
  567. })),
  568. },
  569. };
  570. } catch (err) {
  571. ctx.log(err);
  572. ctx.ajaxErrorBody(err, replaceExisting ? '批量覆盖授权失败' : '批量新增授权失败');
  573. }
  574. }
  575. async getFilingTypePermission(ctx) {
  576. try {
  577. if (ctx.subProject.project_id !== this.ctx.session.sessionProject.id) throw '您无权操作该数据';
  578. const filingType = await ctx.service.subProjPermission.getFilingType(ctx.subProject.id);
  579. ctx.body = { err: 0, msg: '', data: filingType };
  580. } catch(err) {
  581. ctx.log(err);
  582. ctx.ajaxErrorBody(err, '获取授权用户数据错误');
  583. }
  584. }
  585. async saveFilingTypePermission(ctx) {
  586. try {
  587. const data = JSON.parse(ctx.request.body.data);
  588. await ctx.service.subProjPermission.saveFilingType(data);
  589. ctx.body = { err: 0, msg: '', data: '' };
  590. } catch(err) {
  591. ctx.log(err);
  592. ctx.ajaxErrorBody(err, '保存授权用户信息错误');
  593. }
  594. }
  595. async addFiling(ctx) {
  596. try {
  597. this.checkUnlock(ctx);
  598. const data = JSON.parse(ctx.request.body.data);
  599. const filing = await this.getFilingFromDirectoryData(ctx, data);
  600. await this.checkFilingOperation(ctx, filing, 'can_edit_dir');
  601. const result = await ctx.service.filing.add(data);
  602. ctx.body = { err: 0, msg: '', data: result };
  603. } catch (err) {
  604. ctx.log(err);
  605. ctx.ajaxErrorBody(err, '新增分类失败');
  606. }
  607. }
  608. async delFiling(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.del(data);
  615. ctx.body = { err: 0, msg: '', data: result };
  616. } catch (err) {
  617. ctx.log(err);
  618. ctx.ajaxErrorBody(err, '删除分类失败');
  619. }
  620. }
  621. async saveFiling(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.save(data);
  628. ctx.body = { err: 0, msg: '', data: result };
  629. } catch (err) {
  630. ctx.log(err);
  631. ctx.ajaxErrorBody(err, '保存分类数据失败');
  632. }
  633. }
  634. async moveFiling(ctx) {
  635. try {
  636. this.checkUnlock(ctx);
  637. const data = JSON.parse(ctx.request.body.data);
  638. if (!data.id || !(data.tree_order >= 0)) throw '数据错误';
  639. const filing = await this.getFilingFromDirectoryData(ctx, data);
  640. await this.checkFilingOperation(ctx, filing, 'can_edit_dir');
  641. const result = await ctx.service.filing.move(data);
  642. ctx.body = { err: 0, msg: '', data: result };
  643. } catch (err) {
  644. ctx.log(err);
  645. ctx.ajaxErrorBody(err, '移动分类失败');
  646. }
  647. }
  648. async loadFile(ctx) {
  649. try {
  650. const data = JSON.parse(ctx.request.body.data);
  651. const filing = await this.getProjectFiling(ctx, data.filing_id);
  652. await this.checkFilingView(ctx, filing);
  653. const order = data.order.split('|');
  654. if (order.length !== 2) throw '加载文件错误';
  655. if (order[0] !== 'filename' && order[0] !== 'create_time') throw '加载文件错误';
  656. if (order[1] !== 'asc' && order[1] !== 'desc') throw '加载文件错误';
  657. const result = await ctx.service.file.getFiles({
  658. where: { filing_id: data.filing_id, is_deleted: 0 },
  659. orders: [order],
  660. limit: data.count,
  661. offset: (data.page-1)*data.count,
  662. }, order);
  663. ctx.body = { err: 0, msg: '', data: result };
  664. } catch (err) {
  665. ctx.log(err);
  666. ctx.ajaxErrorBody(err, '加载文件失败');
  667. }
  668. }
  669. async checkCanUpload(ctx, filing) {
  670. this.checkUnlock(ctx);
  671. await this.checkFilingOperation(ctx, filing, 'can_upload');
  672. }
  673. async checkFiling(filing) {
  674. const child = await this.ctx.service.filing.getDataByCondition({ tree_pid: filing.id, is_deleted: 0 });
  675. if (child) throw '该分类下存在子分类,请在子分类下上传、导入文件';
  676. }
  677. async checkFiles(ctx) {
  678. try{
  679. const data = JSON.parse(ctx.request.body.data);
  680. if (!data.filing_id || !data.files) throw '缺少参数';
  681. const filing = await this.getProjectFiling(ctx, data.filing_id);
  682. await this.checkCanUpload(ctx, filing);
  683. const result = await ctx.service.file.checkFiles(data.filing_id, data.files);
  684. ctx.body = { err: 0, msg: '', data: result };
  685. } catch(error) {
  686. this.log(error);
  687. ctx.ajaxErrorBody(error, '检查附件错误');
  688. }
  689. }
  690. async uploadFile(ctx){
  691. let stream;
  692. try {
  693. const parts = ctx.multipart({
  694. autoFields: true,
  695. checkFile: this.getFileUploadCheck(ctx),
  696. });
  697. let index = 0;
  698. const create_time = Date.parse(new Date()) / 1000;
  699. stream = await parts();
  700. const user = await ctx. service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  701. const filing = await this.getProjectFiling(ctx, parts.field.filing_id);
  702. await this.checkCanUpload(ctx, filing);
  703. await this.checkFiling(filing);
  704. const uploadfiles = [];
  705. while (stream !== undefined) {
  706. if (!stream.filename) throw '未发现上传文件!';
  707. const fileInfo = path.parse(stream.filename);
  708. const filepath = `sp/file/${filing.spid}/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + index + fileInfo.ext}`;
  709. // 保存文件
  710. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  711. await sendToWormhole(stream);
  712. // 插入到stage_pay对应的附件列表中
  713. uploadfiles.push({
  714. filename: fileInfo.name,
  715. fileext: fileInfo.ext,
  716. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  717. filepath,
  718. });
  719. ++index;
  720. if (Array.isArray(parts.field.size) && index < parts.field.size.length) {
  721. stream = await parts();
  722. } else {
  723. stream = undefined;
  724. }
  725. }
  726. const result = await ctx.service.file.addFiles(filing, uploadfiles, user);
  727. ctx.body = {err: 0, msg: '', data: result };
  728. } catch (error) {
  729. ctx.helper.log(error);
  730. // 失败需要消耗掉stream 以防卡死
  731. if (stream) await sendToWormhole(stream);
  732. ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
  733. }
  734. }
  735. async delFile(ctx) {
  736. try{
  737. this.checkUnlock(ctx);
  738. const data = JSON.parse(ctx.request.body.data);
  739. if (!data.del) throw '缺少参数';
  740. const result = await ctx.service.file.delFiles(data.del);
  741. ctx.body = { err: 0, msg: '', data: result };
  742. } catch(error) {
  743. this.log(error);
  744. ctx.ajaxErrorBody(error, '删除附件失败');
  745. }
  746. }
  747. async saveFile(ctx) {
  748. try {
  749. this.checkUnlock(ctx);
  750. const data = JSON.parse(ctx.request.body.data);
  751. if (!data.id) throw '缺少参数';
  752. const result = await ctx.service.file.saveFile(data.id, data.filename);
  753. ctx.body = { err: 0, msg: '', data: result };
  754. } catch (error) {
  755. this.log(error);
  756. ctx.ajaxErrorBody(error, '编辑附件失败');
  757. }
  758. }
  759. async lockFile(ctx) {
  760. try {
  761. this.checkUnlock(ctx);
  762. const data = JSON.parse(ctx.request.body.data);
  763. if (!data || !data.id) throw '缺少参数';
  764. const result = await ctx.service.file.setLocked(data.id, data.is_locked);
  765. ctx.body = { err: 0, msg: '', data: result };
  766. } catch (error) {
  767. this.log(error);
  768. ctx.ajaxErrorBody(error, '修改文件锁定状态失败');
  769. }
  770. }
  771. async moveFile(ctx) {
  772. try {
  773. this.checkUnlock(ctx);
  774. const data = JSON.parse(ctx.request.body.data);
  775. if (!data.id || !data.filingId) throw '缺少参数';
  776. const targetFiling = await this.getProjectFiling(ctx, data.filingId);
  777. await this.checkFilingOperation(ctx, targetFiling, 'can_upload');
  778. const result = await ctx.service.file.moveFile(data.id, data.filingId);
  779. ctx.body = { err: 0, msg: '', data: result };
  780. } catch (error) {
  781. this.log(error);
  782. ctx.ajaxErrorBody(error, '移动文件失败');
  783. }
  784. }
  785. async uploadBigFile(ctx) {
  786. try {
  787. const data = JSON.parse(ctx.request.body.data);
  788. if (!data.type || !data.filing_id || !data.fileInfo) throw '缺少参数';
  789. const filing = await this.getProjectFiling(ctx, data.filing_id);
  790. await this.checkCanUpload(ctx, filing);
  791. let result;
  792. const fileInfo = path.parse(data.fileInfo.filename);
  793. if (!this.isFileUploadExtensionAllowed(ctx, data.fileInfo.filename)) {
  794. throw `资料管理不支持${fileInfo.ext || '无扩展名'}格式文件`;
  795. }
  796. switch(data.type) {
  797. case 'begin':
  798. const create_time = Date.parse(new Date()) / 1000;
  799. result = {
  800. filename: `sp/file/${filing.spid}/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + fileInfo.ext}`,
  801. };
  802. result.filepath = ctx.app.config.fujianOssFolder + result.filename;
  803. // todo 写入ossToken
  804. result.oss = await ctx.helper.getOssToken(ctx.app.fujianOss);
  805. break;
  806. case 'end':
  807. const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  808. const uploadFiles = [{
  809. filepath: data.filepath,
  810. filename: fileInfo.name, fileext: fileInfo.ext, filesize: data.fileInfo.filesize,
  811. }];
  812. result = await ctx.service.file.addFiles(filing, uploadFiles, user);
  813. break;
  814. }
  815. ctx.body = {err: 0, msg: '', data: result };
  816. } catch (error) {
  817. ctx.log(error);
  818. ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
  819. }
  820. }
  821. async loadValidRelaTender(ctx) {
  822. try {
  823. const data = JSON.parse(ctx.request.body.data);
  824. if (data.type) throw '参数错误';
  825. const accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  826. const userPermission = accountInfo !== undefined && accountInfo.permission !== ''
  827. ? JSON.parse(accountInfo.permission) : null;
  828. const tenders = await ctx.service.tender.getList('', userPermission, ctx.session.sessionUser.is_admin);
  829. for (const r of tenders) {
  830. r.advance = await ctx.service.advance.getAllDataByCondition({ columns: ['id', 'order', 'type'], where: { tid: r.id }});
  831. r.advance.forEach(a => {
  832. const type = advanceConst.typeCol.find(x => { return x.type === a.type });
  833. if (type) a.type_str = type.name;
  834. });
  835. r.stage = await ctx.service.stage.getAllDataByCondition({ columns: ['id', 'order'], where: { tid: r.id, status: auditConst.stage.status.checked } });
  836. r.change = await ctx.service.change.getAllDataByCondition({ columns: ['cid', 'code'], where: { tid: r.id, status: auditConst.flow.status.checked }, orders: [['in_time', 'asc']] });
  837. r.change_apply = await ctx.service.changeApply.getAllDataByCondition({ columns: ['id', 'code'], where: { tid: r.id, status: auditConst.flow.status.checked } });
  838. r.change_plan = await ctx.service.changePlan.getAllDataByCondition({ columns: ['id', 'code'], where: { tid: r.id, status: auditConst.flow.status.checked } });
  839. r.change_project = await ctx.service.changeProject.getAllDataByCondition({ columns: ['id', 'code'], where: { tid: r.id, status: auditConst.flow.status.checked } });
  840. }
  841. const category = await this.ctx.service.category.getAllCategory(ctx.subProject);
  842. ctx.body = {err: 0, msg: '', data: { category, tenders, selfCategoryLevel: this.ctx.subProject.permission.self_category_level} };
  843. } catch (error) {
  844. ctx.helper.log(error);
  845. ctx.body = this.ajaxErrorBody(error, '加载标段信息失败');
  846. }
  847. }
  848. async _loadLedgerAtt(data) {
  849. if (!data.tender_id) throw '参数错误';
  850. return await this.ctx.service.ledgerAtt.getAllDataByCondition({ where: { tid: data.tender_id }, order: [['id', 'desc']]});
  851. }
  852. async _loadStageAtt(data) {
  853. if (!data.tender_id || !data.stage || !data.sub_type) throw '参数错误';
  854. const stage = await this.ctx.service.stage.getDataById(data.stage);
  855. switch (data.sub_type) {
  856. case 'att':
  857. return await this.ctx.service.stageAtt.getAllDataByCondition({ where: { tid: data.tender_id, sid: stage.order }, orders: [['id', 'desc']]});
  858. case 'dealPay':
  859. const payAtt = await this.ctx.service.payAtt.getAllDataByCondition({ where: { sid: stage.id}, orders: [['id', 'desc']] });
  860. return payAtt;
  861. case 'stageIm':
  862. const imFiles = [];
  863. const stageIm = await this.ctx.service.stageDetailAtt.getAllDataByCondition({ where: { sid: stage.id} });
  864. stageIm.forEach(x => {
  865. x.attachment = x.attachment ? JSON.parse(x.attachment) : [];
  866. if (x.attachment.length > 0) imFiles.push(...x.attachment);
  867. });
  868. return imFiles;
  869. }
  870. }
  871. async _loadAdvanceAtt(data) {
  872. if (!data.stage) throw '参数错误';
  873. const self = this;
  874. const result = await this.ctx.service.advanceFile.getAllDataByCondition({ where: { vid: data.stage }, order: [['id', 'desc']]});
  875. result.forEach(x => {
  876. const info = path.parse(x.filename);
  877. x.filename = info.name;
  878. x.filesize = self.ctx.helper.sizeToBytes(x.filesize);
  879. });
  880. return result;
  881. }
  882. async _loadChangeAtt(data) {
  883. if (!data.selectId) throw '参数错误';
  884. const result = await this.ctx.service.changeAtt.getAllDataByCondition({ where: { cid: data.selectId }, order: [['id', 'desc']]});
  885. return result;
  886. }
  887. async _loadChangePlanAtt(data) {
  888. if (!data.selectId) throw '参数错误';
  889. const self = this;
  890. const result = await this.ctx.service.changePlanAtt.getAllDataByCondition({ where: { cpid: data.selectId }, order: [['id', 'desc']]});
  891. result.forEach(x => {
  892. const info = path.parse(x.filename);
  893. x.filename = info.name;
  894. x.filesize = self.ctx.helper.sizeToBytes(x.filesize);
  895. });
  896. return result;
  897. }
  898. async _loadChangeProjectAtt(data) {
  899. if (!data.selectId) throw '参数错误';
  900. const self = this;
  901. const result = await this.ctx.service.changeProjectAtt.getAllDataByCondition({ where: { cpid: data.selectId }, order: [['id', 'desc']]});
  902. result.forEach(x => {
  903. const info = path.parse(x.filename);
  904. x.filename = info.name;
  905. x.filesize = self.ctx.helper.sizeToBytes(x.filesize);
  906. });
  907. return result;
  908. }
  909. async _loadChangeApplyAtt(data) {
  910. if (!data.selectId) throw '参数错误';
  911. const self = this;
  912. const result = await this.ctx.service.changeApplyAtt.getAllDataByCondition({ where: { caid: data.selectId }, order: [['id', 'desc']]});
  913. result.forEach(x => {
  914. const info = path.parse(x.filename);
  915. x.filename = info.name;
  916. x.filesize = self.ctx.helper.sizeToBytes(x.filesize);
  917. });
  918. return result;
  919. }
  920. async loadRelaFiles(ctx) {
  921. try {
  922. const data = JSON.parse(ctx.request.body.data);
  923. if (!data.type) throw '参数错误';
  924. let files;
  925. switch(data.type) {
  926. case 'ledger':
  927. files = await this._loadLedgerAtt(data);
  928. break;
  929. case 'stage':
  930. files = await this._loadStageAtt(data);
  931. break;
  932. case 'advance':
  933. files = await this._loadAdvanceAtt(data);
  934. break;
  935. case 'change':
  936. files = await this._loadChangeAtt(data);
  937. break;
  938. case 'change_plan':
  939. files = await this._loadChangePlanAtt(data);
  940. break;
  941. case 'change_project':
  942. files = await this._loadChangeProjectAtt(data);
  943. break;
  944. case 'change_apply':
  945. files = await this._loadChangeApplyAtt(data);
  946. break;
  947. default: throw '未知文件类型';
  948. }
  949. ctx.body = {err: 0, msg: '', data: files };
  950. } catch (error) {
  951. ctx.helper.log(error);
  952. ctx.body = this.ajaxErrorBody(error, '加载附件失败,请重试');
  953. }
  954. }
  955. async relaFile(ctx) {
  956. try {
  957. const data = JSON.parse(ctx.request.body.data);
  958. if (!data.filing_id || !data.files) throw '缺少参数';
  959. const user = await ctx. service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  960. const filing = await this.getProjectFiling(ctx, data.filing_id);
  961. await this.checkCanUpload(ctx, filing);
  962. await this.checkFiling(filing);
  963. const result = await ctx.service.file.relaFiles(filing, data.files, user);
  964. ctx.body = {err: 0, msg: '', data: result };
  965. } catch (error) {
  966. ctx.helper.log(error);
  967. ctx.body = this.ajaxErrorBody(error, '导入附件失败,请重试');
  968. }
  969. }
  970. async template(ctx) {
  971. const defaultTemplate = await ctx.service.filingTemplateList.getOriginTemplate();
  972. ctx.redirect('/file/template/' + defaultTemplate.id);
  973. }
  974. async templateDetail(ctx) {
  975. try {
  976. const renderData = {
  977. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.template),
  978. };
  979. renderData.templateList = await ctx.service.filingTemplateList.getAllTemplate(ctx.session.sessionProject.id);
  980. renderData.shareTemplate = await ctx.service.filingTemplateList.getShareTemplate(ctx.session.sessionProject.id);
  981. renderData.FtType = ctx.service.filingTemplateList.FtType;
  982. renderData.template = renderData.templateList.find(x => { return x.id === ctx.params.id });
  983. if (!renderData.template) throw '查看的资料模板不存在';
  984. renderData.templateData = await ctx.service.filingTemplate.getData(renderData.template.id);
  985. await this.layout('file/template.ejs', renderData, 'file/template_modal.ejs');
  986. } catch (err) {
  987. ctx.log(err);
  988. ctx.session.postError = err.toString();
  989. ctx.redirect(this.menu.menu.dashboard.url);
  990. }
  991. }
  992. async saveTemplate(ctx) {
  993. try {
  994. const id = ctx.query.id;
  995. const name = ctx.request.body.name;
  996. const is_share = ctx.request.body.is_share ? parseInt(ctx.request.body.is_share) : undefined;
  997. const share_id = ctx.request.body.share_id;
  998. const [save, templateId] = share_id ? await ctx.service.filingTemplateList.copy(share_id) : await ctx.service.filingTemplateList.save(name, is_share, id);
  999. if (!save) throw '保存数据失败';
  1000. ctx.redirect('/file/template/' + templateId);
  1001. } catch(err) {
  1002. ctx.log(err);
  1003. ctx.session.postError = err.toString();
  1004. ctx.redirect('/file/template');
  1005. }
  1006. }
  1007. async resetTemplate(ctx) {
  1008. try {
  1009. const id = ctx.query.id;
  1010. await ctx.service.filingTemplateList.reset(id);
  1011. ctx.redirect('/file/template/' + id);
  1012. } catch (err) {
  1013. ctx.log(err);
  1014. ctx.postError(err, '重置模板失败');
  1015. ctx.redirect('/file/template');
  1016. }
  1017. }
  1018. async delTemplate(ctx) {
  1019. try {
  1020. const id = ctx.query.id;
  1021. await ctx.service.filingTemplateList.delete(id);
  1022. if (ctx.request.headers.referer.indexOf(id) > 0) {
  1023. ctx.redirect('/file/template');
  1024. } else {
  1025. ctx.redirect(ctx.request.headers.referer);
  1026. }
  1027. } catch (err) {
  1028. ctx.log(err);
  1029. ctx.postError(err, '删除模板失败');
  1030. ctx.redirect('/file/template');
  1031. }
  1032. }
  1033. async updateTemplate(ctx) {
  1034. try {
  1035. const data = JSON.parse(ctx.request.body.data);
  1036. if (!data.updateType) throw '数据错误';
  1037. let result;
  1038. if (data.updateType === 'add') {
  1039. result = await ctx.service.filingTemplate.add(ctx.params.id, data);
  1040. } else if (data.updateType === 'del') {
  1041. result = await ctx.service.filingTemplate.del(ctx.params.id, data);
  1042. } else if (data.updateType === 'save') {
  1043. result = await ctx.service.filingTemplate.save(data);
  1044. } else if (data.updateType === 'move') {
  1045. if (!data.id || !(data.tree_order >= 0)) throw '数据错误';
  1046. result = await ctx.service.filingTemplate.move(ctx.params.id, data);
  1047. } else if (data.updateType === 'import') {
  1048. result = await ctx.service.filingTemplate.import(ctx.params.id, data.data);
  1049. } else if (data.updateType === 'multi' ) {
  1050. result = await ctx.service.filingTemplate.multiUpdate(ctx.params.id, data.data);
  1051. }
  1052. ctx.body = { err: 0, msg: '', data: result };
  1053. } catch (err) {
  1054. ctx.log(err);
  1055. ctx.ajaxErrorBody(err, '修改失败');
  1056. }
  1057. }
  1058. async search(ctx) {
  1059. try {
  1060. const limit = 1000;
  1061. const data = JSON.parse(ctx.request.body.data);
  1062. if (!data.keyword) throw '数据错误';
  1063. if (data.filing_id instanceof Array) {
  1064. const filingIds = this.app._.uniq(data.filing_id.map(id => String(id || '')).filter(Boolean));
  1065. if (filingIds.length === 0) throw '数据错误';
  1066. const filings = await ctx.service.filing.getAllDataByCondition({
  1067. where: { id: filingIds, spid: ctx.subProject.id, is_deleted: 0 },
  1068. });
  1069. const permissionMap = await ctx.service.subProjectFilingPermission.getPermissionMap(
  1070. ctx.subProject.id,
  1071. ctx.session.sessionUser.accountId,
  1072. filings,
  1073. ctx.subProject.permission.filing_type,
  1074. ctx.subProject.permission.file_permission,
  1075. this.isAdmin(ctx)
  1076. );
  1077. this.applyFileConfigViewPermission(ctx, permissionMap);
  1078. const validFilingIds = filings.filter(filing => {
  1079. return permissionMap[filing.id] && permissionMap[filing.id].can_view;
  1080. }).map(filing => filing.id);
  1081. const result = await ctx.service.file.searchByFilingIds(validFilingIds, data.keyword, limit);
  1082. ctx.body = { err: 0, msg: '', data: { list: result, limit } };
  1083. return;
  1084. }
  1085. if (!data.filing_type) throw '数据错误';
  1086. const validFilingType = [];
  1087. for (const f of data.filing_type) {
  1088. const filingType = Number(f);
  1089. if (!Number.isInteger(filingType) || filingType <= 0) continue;
  1090. if (ctx.subProject.permission.filing_type === 'all' ||
  1091. ctx.subProject.permission.filing_type.indexOf(filingType) >= 0) validFilingType.push(filingType);
  1092. }
  1093. const result = await ctx.service.file.search(validFilingType, data.keyword, limit);
  1094. ctx.body = { err: 0, msg: '', data: { list: result, limit } };
  1095. } catch(err) {
  1096. ctx.log(err);
  1097. ctx.ajaxErrorBody(err, '搜索文件失败');
  1098. }
  1099. }
  1100. async manage(ctx) {
  1101. try {
  1102. const renderData = {
  1103. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.manage),
  1104. };
  1105. renderData.filingData = await ctx.service.filing.getValidFiling(ctx.params.id, ctx.subProject.permission.filing_type);
  1106. const permissionData = await ctx.service.subProjPermission.getFilingType(ctx.subProject.id);
  1107. permissionData.forEach(x => { x.filing_type = x.filing_type.split(','); });
  1108. renderData.filingData.forEach(x => {
  1109. if (!x.is_fixed) {
  1110. x.permission_count = 0;
  1111. } else {
  1112. const rela = permissionData.filter(y => { return y.filing_type.indexOf(x.filing_type + '') >= 0; });
  1113. x.permission_count = rela.length;
  1114. }
  1115. });
  1116. await this.layout('file/manage.ejs', renderData, 'file/manage_modal.ejs');
  1117. } catch (err) {
  1118. ctx.log(err);
  1119. ctx.session.postError = err.toString();
  1120. ctx.redirect(this.menu.menu.dashboard.url);
  1121. }
  1122. }
  1123. async lockFiling(ctx) {
  1124. try {
  1125. await ctx.service.subProject.save({ id: ctx.subProject.id, lock_file: ctx.query.lock });
  1126. ctx.redirect(`/sp/${ctx.subProject.id}/fm`);
  1127. } catch(err) {
  1128. ctx.log(err);
  1129. ctx.postError(err, '资料归集分类锁定错误');
  1130. ctx.redirect(`/sp/${ctx.subProject.id}/fm`);
  1131. }
  1132. }
  1133. async manageUpdate(ctx) {
  1134. try {
  1135. this.checkLock(ctx);
  1136. const data = JSON.parse(ctx.request.body.data);
  1137. const result = await this.updateFiling(ctx, data);
  1138. ctx.body = { err: 0, msg: '', data: result };
  1139. } catch (err) {
  1140. ctx.log(err);
  1141. ctx.ajaxErrorBody(err, '修改失败');
  1142. }
  1143. }
  1144. async updateFiling(ctx, data) {
  1145. if (!data.updateType) throw '数据错误';
  1146. const updateData = JSON.parse(JSON.stringify(data));
  1147. delete updateData.updateType;
  1148. if (data.updateType === 'add') {
  1149. return await ctx.service.filing.add(updateData);
  1150. } else if (data.updateType === 'del') {
  1151. return await ctx.service.filing.del(updateData);
  1152. } else if (data.updateType === 'save') {
  1153. return await ctx.service.filing.save(updateData);
  1154. } else if (data.updateType === 'edit') {
  1155. return await ctx.service.filing.editDirectory(updateData);
  1156. } else if (data.updateType === 'move') {
  1157. if (!data.id || !(data.tree_order >= 0)) throw '数据错误';
  1158. return await ctx.service.filing.move(updateData);
  1159. } else if (data.updateType === 'multi') {
  1160. return await ctx.service.filing.multiUpdate(ctx.subProject.id, data.data);
  1161. }
  1162. throw '未知的修改类型';
  1163. }
  1164. }
  1165. return FileController;
  1166. };