file_controller.js 59 KB

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