file_controller.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2021/10/27
  7. * @version
  8. */
  9. const auditConst = require('../const/audit');
  10. const sendToWormhole = require('stream-wormhole');
  11. const path = require('path');
  12. const advanceConst = require('../const/advance');
  13. module.exports = app => {
  14. class BudgetController extends app.BaseController {
  15. /**
  16. * 概算投资
  17. *
  18. * @param ctx
  19. * @returns {Promise<void>}
  20. */
  21. async index(ctx) {
  22. try {
  23. if (!ctx.session.sessionProject.page_show.openFile) {
  24. throw '该功能已关闭或无法查看';
  25. }
  26. const renderData = {
  27. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.index),
  28. auditConst,
  29. };
  30. renderData.projectList = await ctx.service.subProject.getFileProject(ctx.session.sessionProject.id, ctx.session.sessionUser.accountId, ctx.session.sessionUser.is_admin);
  31. for (const p of renderData.projectList) {
  32. if (!p.is_folder) p.file_count = await this.service.filing.sumFileCount(p.id);
  33. }
  34. renderData.tenderList = await ctx.service.tender.getList4Select('stage');
  35. renderData.categoryData = await this.ctx.service.category.getAllCategory(this.ctx.session.sessionProject.id);
  36. await this.layout('file/index.ejs', renderData, 'file/modal.ejs');
  37. } catch (err) {
  38. ctx.log(err);
  39. ctx.session.postError = err.toString();
  40. ctx.redirect(this.menu.menu.dashboard.url);
  41. }
  42. }
  43. async file(ctx) {
  44. try {
  45. const renderData = {
  46. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.file),
  47. };
  48. renderData.filing = await ctx.service.filing.getValidFiling(ctx.params.id, ctx.subProject.permission.filing_type);
  49. renderData.categoryData = await ctx.service.category.getAllCategory(ctx.session.sessionProject.id);
  50. renderData.canFiling = ctx.subProject.permission.file_permission.indexOf(ctx.service.subProjPermission.PermissionConst.file.filing.value) >= 0;
  51. renderData.canUpload = ctx.subProject.permission.file_permission.indexOf(ctx.service.subProjPermission.PermissionConst.file.upload.value) >= 0;
  52. renderData.filingTypes = ctx.service.filing.analysisFilingType(renderData.filing);
  53. await this.layout('file/file.ejs', renderData, 'file/file_modal.ejs');
  54. } catch (err) {
  55. ctx.log(err);
  56. }
  57. }
  58. async getFilingTypePermission(ctx) {
  59. try {
  60. if (ctx.subProject.project_id !== this.ctx.session.sessionProject.id) throw '您无权操作该数据';
  61. const filingType = await ctx.service.subProjPermission.getFilingType(ctx.subProject.id);
  62. ctx.body = { err: 0, msg: '', data: filingType };
  63. } catch(err) {
  64. ctx.log(err);
  65. ctx.ajaxErrorBody(err, '获取授权用户数据错误');
  66. }
  67. }
  68. async saveFilingTypePermission(ctx) {
  69. try {
  70. const data = JSON.parse(ctx.request.body.data);
  71. await ctx.service.subProjPermission.saveFilingType(data);
  72. ctx.body = { err: 0, msg: '', data: '' };
  73. } catch(err) {
  74. ctx.log(err);
  75. ctx.ajaxErrorBody(err, '保存授权用户信息错误');
  76. }
  77. }
  78. async addFiling(ctx) {
  79. try {
  80. const data = JSON.parse(ctx.request.body.data);
  81. const result = await ctx.service.filing.add(data);
  82. ctx.body = { err: 0, msg: '', data: result };
  83. } catch (err) {
  84. ctx.log(err);
  85. ctx.ajaxErrorBody(err, '新增分类失败');
  86. }
  87. }
  88. async delFiling(ctx) {
  89. try {
  90. const data = JSON.parse(ctx.request.body.data);
  91. const result = await ctx.service.filing.del(data);
  92. ctx.body = { err: 0, msg: '', data: result };
  93. } catch (err) {
  94. ctx.log(err);
  95. ctx.ajaxErrorBody(err, '删除分类失败');
  96. }
  97. }
  98. async saveFiling(ctx) {
  99. try {
  100. const data = JSON.parse(ctx.request.body.data);
  101. const result = await ctx.service.filing.save(data);
  102. ctx.body = { err: 0, msg: '', data: result };
  103. } catch (err) {
  104. ctx.log(err);
  105. ctx.ajaxErrorBody(err, '保存分类数据失败');
  106. }
  107. }
  108. async moveFiling(ctx) {
  109. try {
  110. const data = JSON.parse(ctx.request.body.data);
  111. if (!data.id || !(data.tree_order >= 0)) throw '数据错误';
  112. const result = await ctx.service.filing.move(data);
  113. ctx.body = { err: 0, msg: '', data: result };
  114. } catch (err) {
  115. ctx.log(err);
  116. ctx.ajaxErrorBody(err, '移动分类失败');
  117. }
  118. }
  119. async loadFile(ctx) {
  120. try {
  121. const data = JSON.parse(ctx.request.body.data);
  122. const order = data.order.split('|');
  123. if (order.length !== 2) throw '加载文件错误';
  124. if (order[0] !== 'filename' && order[0] !== 'create_time') throw '加载文件错误';
  125. if (order[1] !== 'asc' && order[1] !== 'desc') throw '加载文件错误';
  126. const result = await ctx.service.file.getFiles({
  127. where: { filing_id: data.filing_id, is_deleted: 0 },
  128. orders: [order],
  129. limit: data.count,
  130. offset: (data.page-1)*data.count,
  131. }, order);
  132. ctx.body = { err: 0, msg: '', data: result };
  133. } catch (err) {
  134. ctx.log(err);
  135. ctx.ajaxErrorBody(err, '加载文件失败');
  136. }
  137. }
  138. async checkCanUpload(ctx) {
  139. if (ctx.subProject.permission.file_permission.indexOf(ctx.service.subProjPermission.PermissionConst.file.upload.value) < 0) {
  140. throw '您无权上传、导入、删除文件';
  141. }
  142. }
  143. async checkFiling(filing) {
  144. const child = await this.ctx.service.filing.getDataByCondition({ tree_pid: filing.id, is_deleted: 0 });
  145. if (child) throw '该分类下存在子分类,请在子分类下上传、导入文件';
  146. }
  147. async uploadFile(ctx){
  148. let stream;
  149. try {
  150. await this.checkCanUpload(ctx);
  151. const parts = ctx.multipart({ autoFields: true });
  152. let index = 0;
  153. const create_time = Date.parse(new Date()) / 1000;
  154. let stream = await parts();
  155. const user = await ctx. service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  156. const filing = await ctx.service.filing.getDataById(parts.field.filing_id);
  157. if (!filing || filing.is_deleted) throw '分类不存在,请刷新页面后重试';
  158. await this.checkFiling(filing);
  159. const uploadfiles = [];
  160. while (stream !== undefined) {
  161. if (!stream.filename) throw '未发现上传文件!';
  162. const fileInfo = path.parse(stream.filename);
  163. const filepath = `sp/file/${filing.spid}/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + index + fileInfo.ext}`;
  164. // 保存文件
  165. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  166. await sendToWormhole(stream);
  167. // 插入到stage_pay对应的附件列表中
  168. uploadfiles.push({
  169. filename: fileInfo.name,
  170. fileext: fileInfo.ext,
  171. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  172. filepath,
  173. });
  174. ++index;
  175. if (Array.isArray(parts.field.size) && index < parts.field.size.length) {
  176. stream = await parts();
  177. } else {
  178. stream = undefined;
  179. }
  180. }
  181. const result = await ctx.service.file.addFiles(filing, uploadfiles, user);
  182. ctx.body = {err: 0, msg: '', data: result };
  183. } catch (error) {
  184. ctx.helper.log(error);
  185. // 失败需要消耗掉stream 以防卡死
  186. if (stream) await sendToWormhole(stream);
  187. ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
  188. }
  189. }
  190. async delFile(ctx) {
  191. try{
  192. const data = JSON.parse(ctx.request.body.data);
  193. if (!data.del) throw '缺少参数';
  194. const result = await ctx.service.file.delFiles(data.del);
  195. ctx.body = { err: 0, msg: '', data: result };
  196. } catch(error) {
  197. this.log(error);
  198. ctx.ajaxErrorBody(error, '删除附件失败');
  199. }
  200. }
  201. async saveFile(ctx) {
  202. try {
  203. const data = JSON.parse(ctx.request.body.data);
  204. if (!data.id) throw '缺少参数';
  205. const result = await ctx.service.file.saveFile(data.id, data.filename);
  206. ctx.body = { err: 0, msg: '', data: result };
  207. } catch (error) {
  208. this.log(error);
  209. ctx.ajaxErrorBody(error, '编辑附件失败');
  210. }
  211. }
  212. async uploadBigFile(ctx) {
  213. try {
  214. await this.checkCanUpload(ctx);
  215. const data = JSON.parse(ctx.request.body.data);
  216. if (!data.type || !data.filing_id || !data.fileInfo) throw '缺少参数';
  217. const filing = await ctx.service.filing.getDataById(data.filing_id);
  218. if (!filing || filing.is_deleted) throw '分类不存在,请刷新页面后重试';
  219. let result;
  220. const fileInfo = path.parse(data.fileInfo.filename);
  221. switch(data.type) {
  222. case 'begin':
  223. const create_time = Date.parse(new Date()) / 1000;
  224. result = {
  225. filename: `sp/file/${filing.spid}/${ctx.moment().format('YYYYMMDD')}/${create_time + '_' + fileInfo.ext}`,
  226. };
  227. result.filepath = ctx.app.config.fujianOssFolder + result.filename;
  228. // todo 写入ossToken
  229. result.oss = await ctx.helper.getOssToken(ctx.app.fujianOss);
  230. break;
  231. case 'end':
  232. const user = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  233. const uploadFiles = [{
  234. filepath: data.filepath,
  235. filename: fileInfo.name, fileext: fileInfo.ext, filesize: data.fileInfo.filesize,
  236. }];
  237. result = await ctx.service.file.addFiles(filing, uploadFiles, user);
  238. break;
  239. }
  240. ctx.body = {err: 0, msg: '', data: result };
  241. } catch (error) {
  242. ctx.log(error);
  243. ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
  244. }
  245. }
  246. async loadValidRelaTender(ctx) {
  247. try {
  248. const data = JSON.parse(ctx.request.body.data);
  249. if (data.type) throw '参数错误';
  250. const accountInfo = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  251. const userPermission = accountInfo !== undefined && accountInfo.permission !== ''
  252. ? JSON.parse(accountInfo.permission) : null;
  253. const tenderList = await ctx.service.tender.getList('', userPermission, ctx.session.sessionUser.is_admin);
  254. const rela_tender = await ctx.subProject.rela_tender.split(',');
  255. const result = tenderList.filter(x => { return rela_tender.indexOf(x.id + '') >= 0});
  256. for (const r of result) {
  257. r.advance = await ctx.service.advance.getAllDataByCondition({ columns: ['id', 'order', 'type'], where: { tid: r.id }});
  258. r.advance.forEach(a => {
  259. const type = advanceConst.typeCol.find(x => { return x.type === a.type });
  260. if (type) a.type_str = type.name;
  261. });
  262. r.stage = await ctx.service.stage.getAllDataByCondition({ columns: ['id', 'order'], where: { tid: r.id, status: auditConst.stage.status.checked } });
  263. }
  264. ctx.body = {err: 0, msg: '', data: result };
  265. } catch (error) {
  266. ctx.helper.log(error);
  267. ctx.body = this.ajaxErrorBody(error, '加载标段信息失败');
  268. }
  269. }
  270. async _loadLedgerAtt(data) {
  271. if (!data.tender_id) throw '参数错误';
  272. return await this.ctx.service.ledgerAtt.getAllDataByCondition({ where: { tid: data.tender_id }, order: [['id', 'desc']]});
  273. }
  274. async _loadStageAtt(data) {
  275. if (!data.tender_id || !data.stage) throw '参数错误';
  276. switch (data.sub_type) {
  277. case 'att':
  278. const stage = await this.ctx.service.stage.getDataById(data.stage);
  279. return await this.ctx.service.stageAtt.getAllDataByCondition({ where: { tid: data.tender_id, sid: stage.order }, order: [['id', 'desc']]});
  280. }
  281. }
  282. async _loadAdvanceAtt(data) {
  283. if (!data.stage) throw '参数错误';
  284. const self = this;
  285. const result = await this.ctx.service.advanceFile.getAllDataByCondition({ where: { vid: data.stage }, order: [['id', 'desc']]});
  286. result.forEach(x => {
  287. const info = path.parse(x.filename);
  288. x.filename = info.name;
  289. x.filesize = self.ctx.helper.sizeToBytes(x.filesize);
  290. });
  291. return result;
  292. }
  293. async loadRelaFiles(ctx) {
  294. try {
  295. const data = JSON.parse(ctx.request.body.data);
  296. if (!data.type) throw '参数错误';
  297. let files;
  298. switch(data.type) {
  299. case 'ledger':
  300. files = await this._loadLedgerAtt(data);
  301. break;
  302. case 'stage':
  303. files = await this._loadStageAtt(data);
  304. break;
  305. case 'advance':
  306. files = await this._loadAdvanceAtt(data);
  307. break;
  308. default: throw '未知文件类型';
  309. }
  310. ctx.body = {err: 0, msg: '', data: files };
  311. } catch (error) {
  312. ctx.helper.log(error);
  313. ctx.body = this.ajaxErrorBody(error, '加载附件失败,请重试');
  314. }
  315. }
  316. async relaFile(ctx) {
  317. try {
  318. const data = JSON.parse(ctx.request.body.data);
  319. if (!data.filing_id || !data.files) throw '缺少参数';
  320. const user = await ctx. service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  321. const filing = await ctx.service.filing.getDataById(data.filing_id);
  322. if (!filing || filing.is_deleted) throw '分类不存在,请刷新页面后重试';
  323. await this.checkFiling(filing);
  324. const result = await ctx.service.file.relaFiles(filing, data.files, user);
  325. ctx.body = {err: 0, msg: '', data: result };
  326. } catch (error) {
  327. ctx.helper.log(error);
  328. ctx.body = this.ajaxErrorBody(error, '导入附件失败,请重试');
  329. }
  330. }
  331. async template(ctx) {
  332. const defaultTemplate = await ctx.service.filingTemplateList.getOriginTemplate();
  333. ctx.redirect('/file/template/' + defaultTemplate.id);
  334. }
  335. async templateDetail(ctx) {
  336. try {
  337. const renderData = {
  338. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.file.template),
  339. };
  340. renderData.templateList = await ctx.service.filingTemplateList.getAllTemplate(ctx.session.sessionProject.id);
  341. renderData.FtType = ctx.service.filingTemplateList.FtType;
  342. renderData.template = renderData.templateList.find(x => { return x.id === ctx.params.id });
  343. if (!renderData.template) throw '查看的资料模板不存在';
  344. renderData.templateData = await ctx.service.filingTemplate.getData(renderData.template.id);
  345. await this.layout('file/template.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 saveTemplate(ctx) {
  353. try {
  354. const id = ctx.query.id;
  355. const name = ctx.request.body.name;
  356. const [save, templateId] = await ctx.service.filingTemplateList.save(name, id);
  357. if (!save) throw '保存数据失败';
  358. ctx.redirect('/file/template/' + templateId);
  359. } catch(err) {
  360. ctx.log(err);
  361. ctx.session.postError = err.toString();
  362. ctx.redirect('/file/template');
  363. }
  364. }
  365. async resetTemplate(ctx) {
  366. try {
  367. const id = ctx.query.id;
  368. await ctx.service.filingTemplateList.reset(id);
  369. ctx.redirect('/file/template/' + id);
  370. } catch (err) {
  371. ctx.log(err);
  372. ctx.postError(err, '重置模板失败');
  373. ctx.redirect('/file/template');
  374. }
  375. }
  376. async delTemplate(ctx) {
  377. try {
  378. const id = ctx.query.id;
  379. await ctx.service.filingTemplateList.delete(id);
  380. console.log(ctx.request.headers.referer, id);
  381. if (ctx.request.headers.referer.indexOf(id) > 0) {
  382. ctx.redirect('/file/template');
  383. } else {
  384. ctx.redirect(ctx.request.headers.referer);
  385. }
  386. } catch (err) {
  387. ctx.log(err);
  388. ctx.postError(err, '删除模板失败');
  389. ctx.redirect('/file/template');
  390. }
  391. }
  392. async updateTemplate(ctx) {
  393. try {
  394. const data = JSON.parse(ctx.request.body.data);
  395. if (!data.updateType) throw '数据错误';
  396. let result;
  397. if (data.updateType === 'add') {
  398. result = await ctx.service.filingTemplate.add(ctx.params.id, data);
  399. } else if (data.updateType === 'del') {
  400. result = await ctx.service.filingTemplate.del(ctx.params.id, data);
  401. } else if (data.updateType === 'save') {
  402. result = await ctx.service.filingTemplate.save(data);
  403. } else if (data.updateType === 'move') {
  404. if (!data.id || !(data.tree_order >= 0)) throw '数据错误';
  405. result = await ctx.service.filingTemplate.move(ctx.params.id, data);
  406. }
  407. ctx.body = { err: 0, msg: '', data: result };
  408. } catch (err) {
  409. ctx.log(err);
  410. ctx.ajaxErrorBody(err, '修改失败');
  411. }
  412. }
  413. }
  414. return BudgetController;
  415. };