file_controller.js 62 KB

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