file_controller.js 62 KB

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