file_controller.js 62 KB

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