file_controller.js 60 KB

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