file_controller.js 62 KB

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