financial_controller.js 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. 'use strict';
  2. const auditConst = require('../const/audit');
  3. const shenpiConst = require('../const/shenpi');
  4. const financialConst = require('../const/financial');
  5. const moment = require('moment');
  6. const sendToWormhole = require('stream-wormhole');
  7. const fs = require('fs');
  8. const path = require('path');
  9. module.exports = app => {
  10. class FinancialController extends app.BaseController {
  11. /**
  12. * 构造函数
  13. *
  14. * @param {Object} ctx - egg全局变量
  15. * @return {void}
  16. */
  17. constructor(ctx) {
  18. super(ctx);
  19. ctx.showProject = true;
  20. // ctx.showTitle = true;
  21. }
  22. /**
  23. * 资金监管项目列表页
  24. *
  25. * @param {Object} ctx - egg全局页面
  26. * @return {void}
  27. */
  28. async index(ctx) {
  29. try {
  30. if (!ctx.session.sessionProject.page_show.openFinancial) {
  31. throw '该功能已关闭或无法查看';
  32. }
  33. const renderData = {
  34. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.financial.index),
  35. auditConst,
  36. };
  37. renderData.projectList = await ctx.service.subProject.getSubProjectByFinancial(ctx.session.sessionProject.id, ctx.session.sessionUser.accountId, ctx.session.sessionUser.is_admin);
  38. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  39. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  40. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  41. });
  42. for (const proj of renderData.projectList) {
  43. const financialPermission = await ctx.service.financialAudit.getPermission(proj.id, ctx.session.sessionUser.accountId);
  44. if (financialPermission.transfer_show) {
  45. proj.toUrl = 'transfer';
  46. } else if (financialPermission.pay_show) {
  47. proj.toUrl = 'pay';
  48. } else if (!financialPermission.transfer_show && !financialPermission.pay_show) {
  49. proj.toUrl = 'transfer';
  50. }
  51. }
  52. renderData.accountList = accountList;
  53. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({where: {pid: ctx.session.sessionProject.id}});
  54. renderData.accountGroup = unitList.map(item => {
  55. const groupList = accountList.filter(item1 => item1.company === item.name);
  56. return { groupName: item.name, groupList };
  57. });
  58. // renderData.permissionConst = ctx.service.subProjPermission.PermissionConst;
  59. renderData.categoryData = await this.ctx.service.category.getAllCategory(this.ctx.session.sessionProject.id);
  60. renderData.companys = await this.ctx.service.constructionUnit.getAllDataByCondition({where: {pid: ctx.session.sessionProject.id}});
  61. // renderData.templates = await this.ctx.service.filingTemplateList.getAllTemplate(ctx.session.sessionProject.id);
  62. await this.layout('financial/index.ejs', renderData, 'financial/modal.ejs');
  63. } catch (err) {
  64. ctx.log(err);
  65. ctx.session.postError = err.toString();
  66. ctx.redirect(this.menu.menu.dashboard.url);
  67. }
  68. }
  69. async auditSave(ctx) {
  70. try {
  71. if (ctx.session.sessionUser.is_admin === 0) throw '没有设置权限';
  72. const responseData = {
  73. err: 0, msg: '', data: null,
  74. };
  75. const data = JSON.parse(ctx.request.body.data);
  76. if (!data.type) {
  77. throw '提交数据错误';
  78. }
  79. let uids;
  80. let result = false;
  81. let auditList = [];
  82. switch (data.type) {
  83. case 'add-audit':
  84. // 判断用户是单个还是数组
  85. uids = data.id instanceof Array ? data.id : [data.id];
  86. // 判断该用户的组是否已加入到表中,已加入则提示无需添加
  87. auditList = await ctx.service.financialAudit.getAllDataByCondition({ where: { spid: ctx.subProject.id } });
  88. const addAidList = ctx.helper._.difference(uids, ctx.helper._.map(auditList, 'uid'));
  89. if (addAidList.length === 0) {
  90. throw '用户已存在成员管理中,无需重复添加';
  91. }
  92. const accountList = await ctx.service.projectAccount.getAllDataByCondition({ where: { id: addAidList } });
  93. await ctx.service.financialAudit.saveAudits(ctx.subProject.id, accountList);
  94. responseData.data = await ctx.service.financialAudit.getList(ctx.subProject.id);
  95. break;
  96. case 'del-audit':
  97. uids = data.id instanceof Array ? data.id : [data.id];
  98. auditList = await ctx.service.financialAudit.getAllDataByCondition({ where: { spid: ctx.subProject.id, id: uids } });
  99. if (auditList.length !== uids.length) {
  100. throw '该用户已不存在成员管理中,移除失败';
  101. }
  102. await ctx.service.financialAudit.delAudit(uids);
  103. responseData.data = await ctx.service.financialAudit.getList(ctx.subProject.id);
  104. break;
  105. case 'save-permission':
  106. result = await ctx.service.financialAudit.updatePermission(data.updateData);
  107. if (!result) {
  108. throw '修改权限失败';
  109. }
  110. break;
  111. case 'list':
  112. responseData.data = await ctx.service.financialAudit.getList(ctx.subProject.id);
  113. break;
  114. default: throw '参数有误';
  115. }
  116. ctx.body = responseData;
  117. } catch (err) {
  118. this.log(err);
  119. ctx.body = { err: 1, msg: err.toString(), data: null };
  120. }
  121. }
  122. async transfer(ctx) {
  123. try {
  124. const financialPermission = await ctx.service.financialAudit.getPermission(ctx.subProject.id, ctx.session.sessionUser.accountId);
  125. if (!financialPermission.transfer_show) {
  126. throw '没有查看权限';
  127. }
  128. const transferList = await ctx.service.financialTransfer.getList(ctx.subProject.id);
  129. const renderData = {
  130. financialPermission,
  131. transferList,
  132. moment,
  133. preUrl: '/financial',
  134. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.financial.transfer),
  135. whiteList: ctx.app.config.multipart.whitelist,
  136. };
  137. await this.layout('financial/transfer.ejs', renderData, 'financial/transfer_modal.ejs');
  138. } catch (err) {
  139. ctx.log(err);
  140. console.log(err);
  141. ctx.session.postError = err.toString();
  142. ctx.redirect('/financial');
  143. }
  144. }
  145. async transferAdd(ctx) {
  146. try {
  147. const financialPermission = await ctx.service.financialAudit.getPermission(ctx.subProject.id, ctx.session.sessionUser.accountId);
  148. if (!financialPermission.transfer_add) {
  149. throw '没有添加权限';
  150. }
  151. const date = ctx.request.body.date;
  152. const remark = ctx.request.body.remark;
  153. if (!date) {
  154. throw '请选择划拨年月';
  155. }
  156. const newTransferId = await ctx.service.financialTransfer.addTransfer(ctx.subProject.id, date, remark);
  157. if (!newTransferId) {
  158. throw '新增资金划拨失败,请重试';
  159. }
  160. ctx.redirect('/financial/' + ctx.subProject.id + '/transfer/' + newTransferId + '/tender');
  161. } catch (err) {
  162. console.log(err);
  163. ctx.postError(err, '新增资金划拨失败');
  164. ctx.redirect(ctx.request.header.referer);
  165. }
  166. }
  167. async transferTender(ctx) {
  168. try {
  169. const financialPermission = await ctx.service.financialAudit.getPermission(ctx.subProject.id, ctx.session.sessionUser.accountId);
  170. if (!financialPermission.transfer_show) {
  171. throw '没有查看权限';
  172. }
  173. const trid = ctx.params.id;
  174. const transferInfo = await ctx.service.financialTransfer.getDataById(trid);
  175. if (!transferInfo) {
  176. throw '该资金划拨信息不存在';
  177. }
  178. const transferTenderList = await ctx.service.financialTransferTender.getList(trid);
  179. const tenders = await ctx.service.tender.getAllDataByCondition({ where: { spid: ctx.subProject.id } });
  180. for (const tt of transferTenderList) {
  181. const tenderIndex = ctx.helper._.findIndex(tenders, { id: tt.tid });
  182. if (tenderIndex !== -1) {
  183. tenders.splice(tenderIndex, 1);
  184. }
  185. }
  186. const allTransferTenders = await ctx.service.financialTransferTender.getAllDataByCondition({ where: { spid: ctx.subProject.id } });
  187. for (const t of tenders) {
  188. const stages = await ctx.service.stage.getAllDataByCondition({ where: { tid: t.id, status: auditConst.stage.status.checked } });
  189. const allTenderStages = ctx.helper._.filter(allTransferTenders, { tid: t.id });
  190. for (const ts of allTenderStages) {
  191. const sorderArray = ts.sorder ? ts.sorder.split(',') : [];
  192. for (const sorder of sorderArray) {
  193. const stageIndex = ctx.helper._.findIndex(stages, function(item) {
  194. return item.order === parseInt(sorder);
  195. });
  196. if (stageIndex !== -1) {
  197. stages.splice(stageIndex, 1);
  198. }
  199. }
  200. }
  201. t.stages = stages;
  202. }
  203. const renderData = {
  204. financialPermission,
  205. transferInfo,
  206. transferTenderList,
  207. tenders,
  208. moment,
  209. preUrl: '/financial/' + ctx.subProject.id + '/transfer',
  210. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.financial.transferTender),
  211. whiteList: ctx.app.config.multipart.whitelist,
  212. };
  213. await this.layout('financial/transfer_tender.ejs', renderData, 'financial/transfer_tender_modal.ejs');
  214. } catch (err) {
  215. ctx.log(err);
  216. console.log(err);
  217. ctx.session.postError = err.toString();
  218. ctx.redirect('/financial');
  219. }
  220. }
  221. async transferUpdate(ctx) {
  222. try {
  223. const data = JSON.parse(ctx.request.body.data);
  224. if (!data.postType || !data.postData) throw '数据错误';
  225. const responseData = { err: 0, msg: '', data: {} };
  226. switch (data.postType) {
  227. case 'del-transfer':
  228. responseData.data = await ctx.service.financialTransfer.delTransfer(data.postData.node);
  229. break;
  230. case 'lock-transfer':
  231. responseData.data = await ctx.service.financialTransfer.lockTransfer(data.postData.node, data.postData.lock);
  232. break;
  233. case 'save-transfer':
  234. responseData.data = await ctx.service.financialTransfer.saveTransfer(data.postData);
  235. break;
  236. default:
  237. throw '未知操作';
  238. }
  239. ctx.body = responseData;
  240. } catch (err) {
  241. console.log(err);
  242. this.log(err);
  243. ctx.body = this.ajaxErrorBody(err, '数据错误');
  244. }
  245. }
  246. async transferTenderUpdate(ctx) {
  247. try {
  248. const financialPermission = await ctx.service.financialAudit.getPermission(ctx.subProject.id, ctx.session.sessionUser.accountId);
  249. if (!financialPermission.transfer_add) {
  250. throw '没有权限';
  251. }
  252. const trid = ctx.params.id;
  253. const transferInfo = await ctx.service.financialTransfer.getDataById(trid);
  254. if (!transferInfo) {
  255. throw '该资金划拨信息不存在';
  256. }
  257. if (transferInfo.uid !== ctx.session.sessionUser.accountId) {
  258. throw '不是你创建的没有权限操作';
  259. }
  260. const data = JSON.parse(ctx.request.body.data);
  261. if (!data.postType || !data.postData) throw '数据错误';
  262. const responseData = { err: 0, msg: '', data: {} };
  263. switch (data.postType) {
  264. case 'add-tender':
  265. const result = await ctx.service.financialTransferTender.addTenders(transferInfo, data.postData.tenders);
  266. if (!result) {
  267. throw '新增失败';
  268. }
  269. break;
  270. case 'del-tender':
  271. responseData.data = await ctx.service.financialTransferTender.delTenders(data.postData.node);
  272. break;
  273. case 'update-hb_tp':
  274. responseData.data = await ctx.service.financialTransferTender.updateHbTp(data.postData.node, data.postData.hb_tp);
  275. break;
  276. default:
  277. throw '未知操作';
  278. }
  279. ctx.body = responseData;
  280. } catch (err) {
  281. console.log(err);
  282. this.log(err);
  283. ctx.body = this.ajaxErrorBody(err, '数据错误');
  284. }
  285. }
  286. /**
  287. * 上传附件
  288. * @param {*} ctx 上下文
  289. */
  290. async transferUploadFile(ctx) {
  291. let stream;
  292. try {
  293. const financialPermission = await ctx.service.financialAudit.getPermission(ctx.subProject.id, ctx.session.sessionUser.accountId);
  294. if (!financialPermission.transfer_file) {
  295. throw '没有权限';
  296. }
  297. const responseData = { err: 0, msg: '', data: {} };
  298. const id = ctx.params.id;
  299. if (!id) throw '参数有误';
  300. const parts = this.ctx.multipart({
  301. autoFields: true,
  302. });
  303. const files = [];
  304. const create_time = Date.parse(new Date()) / 1000;
  305. let idx = 0;
  306. while ((stream = await parts()) !== undefined) {
  307. if (!stream.filename) {
  308. // 如果没有传入直接返回
  309. return;
  310. }
  311. const fileInfo = path.parse(stream.filename);
  312. const filepath = `sp/financial/${ctx.subProject.id}/transfer/${id}/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  313. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  314. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  315. ++idx;
  316. stream && (await sendToWormhole(stream));
  317. }
  318. const in_time = new Date();
  319. const payload = files.map(file => {
  320. let idx;
  321. if (Array.isArray(parts.field.name)) {
  322. idx = parts.field.name.findIndex(name => name === file.name);
  323. } else {
  324. idx = 'isString';
  325. }
  326. const newFile = {
  327. spid: ctx.subProject.id,
  328. trid: id,
  329. uid: ctx.session.sessionUser.accountId,
  330. filename: file.name,
  331. fileext: file.ext,
  332. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  333. filepath: file.filepath,
  334. upload_time: in_time,
  335. };
  336. return newFile;
  337. });
  338. // 执行文件信息写入数据库
  339. await ctx.service.financialTransferAtt.saveFileMsgToDb(payload);
  340. // 将最新的当前标段的所有文件信息返回
  341. responseData.data = await ctx.service.financialTransferAtt.getAtt(id);
  342. ctx.body = responseData;
  343. } catch (err) {
  344. stream && (await sendToWormhole(stream));
  345. this.log(err);
  346. ctx.body = { err: 1, msg: err.toString(), data: null };
  347. }
  348. }
  349. /**
  350. * 删除附件
  351. * @param {Ojbect} ctx 上下文
  352. */
  353. async transferDeleteFile(ctx) {
  354. try {
  355. const id = ctx.params.id;
  356. const responseData = { err: 0, msg: '', data: {} };
  357. const data = JSON.parse(ctx.request.body.data);
  358. const fileInfo = await ctx.service.financialTransferAtt.getDataById(data.id);
  359. if (fileInfo || Object.keys(fileInfo).length) {
  360. // 先删除文件
  361. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  362. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  363. // 再删除数据库
  364. await ctx.service.financialTransferAtt.delete(data.id);
  365. } else {
  366. throw '不存在该文件';
  367. }
  368. responseData.data = await ctx.service.financialTransferAtt.getAtt(id);
  369. ctx.body = responseData;
  370. } catch (err) {
  371. this.log(err);
  372. ctx.body = { err: 1, msg: err.toString(), data: null };
  373. }
  374. }
  375. /**
  376. * 下载附件
  377. * @param {Object} ctx - egg全局变量
  378. * @return {void}
  379. */
  380. async transferDownloadFile(ctx) {
  381. const id = ctx.params.fid;
  382. if (id) {
  383. try {
  384. const fileInfo = await ctx.service.financialTransferAtt.getDataById(id);
  385. if (fileInfo) {
  386. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  387. // 解决中文无法下载问题
  388. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  389. let disposition = '';
  390. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  391. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  392. } else if (userAgent.indexOf('firefox') >= 0) {
  393. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  394. } else {
  395. /* safari等其他非主流浏览器只能自求多福了 */
  396. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  397. }
  398. ctx.response.set({
  399. 'Content-Type': 'application/octet-stream',
  400. 'Content-Disposition': disposition,
  401. 'Content-Length': fileInfo.filesize,
  402. });
  403. // ctx.body = await fs.createReadStream(fileName);
  404. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  405. } else {
  406. throw '不存在该文件';
  407. }
  408. } catch (err) {
  409. this.log(err);
  410. this.setMessage(err.toString(), this.messageType.ERROR);
  411. }
  412. }
  413. }
  414. /**
  415. * 上传附件
  416. * @param {*} ctx 上下文
  417. */
  418. async transferTenderUploadFile(ctx) {
  419. let stream;
  420. try {
  421. const financialPermission = await ctx.service.financialAudit.getPermission(ctx.subProject.id, ctx.session.sessionUser.accountId);
  422. if (!financialPermission.transfer_file) {
  423. throw '没有权限';
  424. }
  425. const responseData = { err: 0, msg: '', data: {} };
  426. const trid = ctx.params.trid;
  427. const id = ctx.params.id;
  428. if (!id) throw '参数有误';
  429. const parts = this.ctx.multipart({
  430. autoFields: true,
  431. });
  432. const files = [];
  433. const create_time = Date.parse(new Date()) / 1000;
  434. let idx = 0;
  435. while ((stream = await parts()) !== undefined) {
  436. if (!stream.filename) {
  437. // 如果没有传入直接返回
  438. return;
  439. }
  440. const fileInfo = path.parse(stream.filename);
  441. const filepath = `sp/financial/${ctx.subProject.id}/transfer/${trid}/tender/${id}/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  442. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  443. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  444. ++idx;
  445. stream && (await sendToWormhole(stream));
  446. }
  447. const in_time = new Date();
  448. const payload = files.map(file => {
  449. let idx;
  450. if (Array.isArray(parts.field.name)) {
  451. idx = parts.field.name.findIndex(name => name === file.name);
  452. } else {
  453. idx = 'isString';
  454. }
  455. const newFile = {
  456. spid: ctx.subProject.id,
  457. trid,
  458. ftid: id,
  459. uid: ctx.session.sessionUser.accountId,
  460. filename: file.name,
  461. fileext: file.ext,
  462. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  463. filepath: file.filepath,
  464. upload_time: in_time,
  465. };
  466. return newFile;
  467. });
  468. // 执行文件信息写入数据库
  469. await ctx.service.financialTransferTenderAtt.saveFileMsgToDb(payload);
  470. // 将最新的当前标段的所有文件信息返回
  471. responseData.data = await ctx.service.financialTransferTenderAtt.getAtt(id);
  472. ctx.body = responseData;
  473. } catch (err) {
  474. stream && (await sendToWormhole(stream));
  475. this.log(err);
  476. ctx.body = { err: 1, msg: err.toString(), data: null };
  477. }
  478. }
  479. /**
  480. * 删除附件
  481. * @param {Ojbect} ctx 上下文
  482. */
  483. async transferTenderDeleteFile(ctx) {
  484. try {
  485. const id = ctx.params.id;
  486. const responseData = { err: 0, msg: '', data: {} };
  487. const data = JSON.parse(ctx.request.body.data);
  488. const fileInfo = await ctx.service.financialTransferTenderAtt.getDataById(data.id);
  489. if (fileInfo || Object.keys(fileInfo).length) {
  490. // 先删除文件
  491. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  492. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  493. // 再删除数据库
  494. await ctx.service.financialTransferTenderAtt.delete(data.id);
  495. } else {
  496. throw '不存在该文件';
  497. }
  498. responseData.data = await ctx.service.financialTransferTenderAtt.getAtt(id);
  499. ctx.body = responseData;
  500. } catch (err) {
  501. this.log(err);
  502. ctx.body = { err: 1, msg: err.toString(), data: null };
  503. }
  504. }
  505. /**
  506. * 下载附件
  507. * @param {Object} ctx - egg全局变量
  508. * @return {void}
  509. */
  510. async transferTenderDownloadFile(ctx) {
  511. const id = ctx.params.fid;
  512. if (id) {
  513. try {
  514. const fileInfo = await ctx.service.financialTransferTenderAtt.getDataById(id);
  515. if (fileInfo) {
  516. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  517. // 解决中文无法下载问题
  518. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  519. let disposition = '';
  520. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  521. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  522. } else if (userAgent.indexOf('firefox') >= 0) {
  523. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  524. } else {
  525. /* safari等其他非主流浏览器只能自求多福了 */
  526. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  527. }
  528. ctx.response.set({
  529. 'Content-Type': 'application/octet-stream',
  530. 'Content-Disposition': disposition,
  531. 'Content-Length': fileInfo.filesize,
  532. });
  533. // ctx.body = await fs.createReadStream(fileName);
  534. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  535. } else {
  536. throw '不存在该文件';
  537. }
  538. } catch (err) {
  539. this.log(err);
  540. this.setMessage(err.toString(), this.messageType.ERROR);
  541. }
  542. }
  543. }
  544. /**
  545. * 变更管理 页面 (Get)
  546. *
  547. * @param {Object} ctx - egg全局变量
  548. * @return {void}
  549. */
  550. async pay(ctx) {
  551. try {
  552. const status = parseInt(ctx.query.status) || 0;
  553. const tid = parseInt(ctx.query.tid) || null;
  554. const used = ctx.query.used || null;
  555. await this._filterPay(ctx, status, tid, used);
  556. } catch (err) {
  557. this.log(err);
  558. ctx.redirect('/financial');
  559. }
  560. }
  561. // /**
  562. // * 变更管理 状态筛选 页面 (Get)
  563. // * @param {Object} ctx - egg全局变量
  564. // * @return {void}
  565. // */
  566. // async payStatus(ctx) {
  567. // try {
  568. // const status = parseInt(ctx.query.status);
  569. // const tid = parseInt(ctx.params.tid) || null;
  570. // const used = ctx.params.used || null;
  571. // await this._filterPay(ctx, status, tid, used);
  572. // } catch (err) {
  573. // this.logger.error(err);
  574. // ctx.redirect('/financial');
  575. // }
  576. // }
  577. async _filterPay(ctx, status = 0, tid = null, used = null) {
  578. const financialPermission = await ctx.service.financialAudit.getPermission(ctx.subProject.id, ctx.session.sessionUser.accountId);
  579. if (!financialPermission.pay_show) {
  580. throw '没有查看权限';
  581. }
  582. const fptAudits = await ctx.service.financialPayTenderAudit.getAllDataByCondition({ where: { spid: ctx.subProject.id, uid: ctx.session.sessionUser.accountId } });
  583. const fptAuditTids = ctx.helper._.map(fptAudits, 'tid');
  584. const filterTids = tid === null ? (ctx.session.sessionUser.is_admin ? null : fptAuditTids) : [tid];
  585. const tenderCondition = { spid: ctx.subProject.id };
  586. let hadTender = false;
  587. if (ctx.session.sessionUser.is_admin) {
  588. hadTender = true;
  589. } else if (fptAuditTids.length !== 0) {
  590. hadTender = true;
  591. tenderCondition.id = fptAuditTids;
  592. } else {
  593. hadTender = false;
  594. tenderCondition.id = -1;
  595. }
  596. const tenders = hadTender ? await ctx.service.tender.getAllDataByCondition({ where: tenderCondition, columns: ['id', 'name'] }) : [];
  597. const filter = JSON.parse(JSON.stringify(auditConst.financial.filter));
  598. filter.count = [];
  599. filter.count[filter.status.pending] = await ctx.service.financialPay.getCountByStatus(ctx.subProject.id, filter.status.pending, filterTids, used);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  600. filter.count[filter.status.uncheck] = await ctx.service.financialPay.getCountByStatus(ctx.subProject.id, filter.status.uncheck, filterTids, used);// await ctx.service.change.checkingDatas(tender.id, ctx.session.sessionUser.accountId);
  601. filter.count[filter.status.checking] = await ctx.service.financialPay.getCountByStatus(ctx.subProject.id, filter.status.checking, filterTids, used);// await ctx.service.change.checkedDatas(tender.id, ctx.session.sessionUser.accountId);
  602. filter.count[filter.status.checked] = await ctx.service.financialPay.getCountByStatus(ctx.subProject.id, filter.status.checked, filterTids, used);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  603. const payList = await ctx.service.financialPay.getListByStatus(ctx.subProject.id, status, filterTids, used);
  604. // 获取所有项目参与者
  605. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  606. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  607. columns: ['id', 'account', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  608. });
  609. const payTenders = await ctx.service.financialPayTender.getAllDataByCondition({ where: { spid: ctx.subProject.id } });
  610. for (const t of tenders) {
  611. const fptReportTids = ctx.helper._.map(ctx.helper._.filter(fptAudits, { is_report: 1 }), 'tid');
  612. const info = await ctx.service.tenderInfo.getDataByCondition({ tid: t.id });
  613. t.pay_account = info && info.pay_account ? JSON.parse(info.pay_account).project : '';
  614. const pt = ctx.helper._.find(payTenders, { tid: t.id });
  615. t.pt = pt ? pt : { id: 0, tid: t.id, name: '', bank: '', bank_account: '', contact: '', phone: '' };
  616. if (ctx.session.sessionUser.is_admin || ctx.helper._.includes(fptReportTids, t.id)) {
  617. t.dealCode = info && info.deal_info ? JSON.parse(info.deal_info).dealCode : '';
  618. const lastPay = await ctx.service.financialPay.getAllDataByCondition({ where: { spid: ctx.subProject.id, tid: t.id }, columns: ['code'], orders: [['id', 'desc']], limit: 1 });
  619. t.startNum = 1;
  620. if (lastPay.length > 0) {
  621. const startArray = lastPay[0].code.split('-');
  622. t.startNum = parseInt(startArray[startArray.length - 1]) + 1;
  623. }
  624. }
  625. }
  626. for (const pay of payList) {
  627. const t = ctx.helper._.find(tenders, { id: pay.tid });
  628. pay.tenderName = t ? t.name : '';
  629. const userInfo = ctx.helper._.find(accountList, { id: pay.uid });
  630. pay.username = userInfo ? userInfo.name : '';
  631. if (pay.status !== auditConst.financial.status.checked || !pay.final_auditor_str) {
  632. pay.curAuditors = await ctx.service.financialPayAudit.getAuditorsByStatus(pay.id, pay.status, pay.times);
  633. if (pay.status === auditConst.financial.status.checked && pay.curAuditors.length > 0) {
  634. const final_auditor_str = pay.curAuditors[0].audit_type === auditConst.auditType.key.common
  635. ? pay.curAuditors[0].name + (pay.curAuditors[0].role ? '-' + pay.curAuditors[0].role : '')
  636. : ctx.helper.transFormToChinese(pay.curAuditors[0].audit_order) + '审';
  637. await ctx.service.financialPay.defaultUpdate({ final_auditor_str }, { where: { id: pay.id } });
  638. }
  639. }
  640. if (pay.status === auditConst.financial.status.uncheck || pay.status === auditConst.financial.status.checkNo) {
  641. pay.entities = await ctx.service.financialPayContract.getEntities(pay.id);
  642. }
  643. }
  644. if (ctx.session.sessionUser.is_admin) {
  645. for (const t of tenders) {
  646. t.permissionList = await ctx.service.financialPayTenderAudit.getList(ctx.subProject.id, t.id, accountList);
  647. t.auditGroupList = await ctx.service.shenpiAudit.getAuditGroupList(t.id, shenpiConst.sp_other_type.financial, shenpiConst.sp_status.gdspl);
  648. }
  649. }
  650. const renderData = {
  651. tenders,
  652. financialPermission,
  653. usedList: financialConst.used,
  654. auditConst: auditConst.financial,
  655. filter,
  656. tid,
  657. status,
  658. used,
  659. payList,
  660. fptAuditTids,
  661. moment,
  662. auditType: auditConst.auditType,
  663. preUrl: '/financial',
  664. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.financial.pay),
  665. };
  666. if (ctx.session.sessionUser.is_admin) {
  667. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  668. renderData.accountList = accountList;
  669. renderData.accountGroup = unitList.map(item => {
  670. const groupList = accountList.filter(item1 => item1.company === item.name);
  671. return { groupName: item.name, groupList };
  672. });
  673. renderData.auditType = auditConst.auditType;
  674. renderData.shenpi = shenpiConst;
  675. }
  676. await this.layout('financial/pay.ejs', renderData, 'financial/pay_modal.ejs');
  677. }
  678. async paySave(ctx) {
  679. try {
  680. const responseData = {
  681. err: 0, msg: '', data: {},
  682. };
  683. const data = JSON.parse(ctx.request.body.data);
  684. if (!data.type) {
  685. throw '提交数据错误';
  686. }
  687. let uids;
  688. let result = false;
  689. let auditList = [];
  690. switch (data.type) {
  691. case 'add-tender-audit':
  692. // 判断用户是单个还是数组
  693. if (!data.tid) throw '参数有误';
  694. uids = data.id instanceof Array ? data.id : [data.id];
  695. // 判断该用户的组是否已加入到表中,已加入则提示无需添加
  696. auditList = await ctx.service.financialPayTenderAudit.getAllDataByCondition({ where: { spid: ctx.subProject.id, tid: data.tid } });
  697. const addAidList = ctx.helper._.difference(uids, ctx.helper._.map(auditList, 'uid'));
  698. if (addAidList.length === 0) {
  699. throw '用户已存在填报人列表中,无需重复添加';
  700. }
  701. const accountList = await ctx.service.projectAccount.getAllDataByCondition({ where: { id: addAidList } });
  702. await ctx.service.financialPayTenderAudit.saveAudits(ctx.subProject.id, data.tid, accountList);
  703. responseData.data = await ctx.service.financialPayTenderAudit.getList(ctx.subProject.id, data.tid);
  704. break;
  705. case 'del-tender-audit':
  706. if (!data.tid) throw '参数有误';
  707. uids = data.id instanceof Array ? data.id : [data.id];
  708. auditList = await ctx.service.financialPayTenderAudit.getAllDataByCondition({ where: { id: uids } });
  709. if (auditList.length !== uids.length) {
  710. throw '该用户已不存在填报人列表中,移除失败';
  711. }
  712. responseData.data = await ctx.service.financialPayTenderAudit.delAudits(ctx.subProject.id, data.tid, auditList);
  713. // responseData.data = await ctx.service.financialPayTenderAudit.getList(ctx.subProject.id, data.tid);
  714. break;
  715. case 'save-permission':
  716. result = await ctx.service.financialPayTenderAudit.updatePermission(data.updateData);
  717. if (!result) {
  718. throw '修改权限失败';
  719. }
  720. break;
  721. case 'copy-tender-audit':
  722. responseData.data = await ctx.service.financialPayTenderAudit.copyAudit2otherTender(ctx.subProject.id, data, data.this_tid);
  723. break;
  724. case 'add-shenpi-audit':
  725. responseData.data = await ctx.service.financialPayTenderAudit.addShenpiAudit(ctx.subProject.id, data.shenpi, data.tid);
  726. break;
  727. case 'copy-shenpi-audit':
  728. responseData.data = await ctx.service.financialPayTenderAudit.copyShenpi2otherTender(ctx.subProject.id, data, data.this_tid);
  729. break;
  730. case 'add-pay':
  731. responseData.data = await ctx.service.financialPay.addPay(ctx.subProject.id, data.updateData);
  732. break;
  733. case 'del-pay':
  734. responseData.data = await ctx.service.financialPay.delPay(data.postData.node);
  735. break;
  736. case 'set-pay-tender':
  737. responseData.data = await ctx.service.financialPayTender.savePayTender(ctx.subProject.id, data.updateData);
  738. break;
  739. case 'get-auditors':
  740. const fpInfo = await ctx.service.financialPay.getDataById(data.id);
  741. await ctx.service.financialPay.loadPayUser(fpInfo);
  742. await ctx.service.financialPay.loadFinancialPayAuditViewData(fpInfo);
  743. responseData.data = fpInfo;
  744. break;
  745. default: throw '参数有误';
  746. }
  747. ctx.body = responseData;
  748. } catch (err) {
  749. this.log(err);
  750. ctx.body = { err: 1, msg: err.toString(), data: {} };
  751. }
  752. }
  753. /**
  754. * 获取审批界面所需的 原报、审批人数据等
  755. * @param ctx
  756. * @return {Promise<void>}
  757. * @private
  758. */
  759. async _getFinancialAuditViewData(ctx) {
  760. await ctx.service.financialPay.loadFinancialPayAuditViewData(ctx.financialPay);
  761. }
  762. async payDetail(ctx) {
  763. try {
  764. if (!ctx.financialPay.permission.pay_show) {
  765. throw '没有查看权限';
  766. }
  767. await this._getFinancialAuditViewData(ctx);
  768. // 获取附件列表
  769. const fileList = await ctx.service.financialPayAtt.getAtt(ctx.financialPay.id);
  770. const renderData = {
  771. financialPermission: ctx.financialPay.permission,
  772. financialPay: ctx.financialPay,
  773. usedList: financialConst.used,
  774. payTypeList: financialConst.pay_type,
  775. auditConst: auditConst.financial,
  776. auditType: auditConst.auditType,
  777. whiteList: ctx.app.config.multipart.whitelist,
  778. moment,
  779. fileList,
  780. preUrl: '/financial/' + ctx.subProject.id + '/pay',
  781. preUrl2: '/financial/' + ctx.subProject.id + '/pay/' + ctx.financialPay.id,
  782. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.financial.payDetail),
  783. };
  784. await this.layout('financial/pay_detail.ejs', renderData, 'financial/pay_detail_modal.ejs');
  785. } catch (err) {
  786. this.log(err);
  787. ctx.redirect('/financial');
  788. }
  789. }
  790. /**
  791. * 上报和重新上报
  792. * @param ctx
  793. * @return {Promise<void>}
  794. */
  795. async startPayAudit(ctx) {
  796. try {
  797. // 检查权限等
  798. if (!ctx.financialPay) {
  799. throw '数据错误';
  800. }
  801. if (ctx.financialPay.uid !== ctx.session.sessionUser.accountId) {
  802. throw '您无权上报该资金支付数据';
  803. }
  804. if (ctx.financialPay.status === auditConst.financial.status.checking || ctx.financialPay.status === auditConst.financial.status.checked) {
  805. throw '该资金支付数据当前无法上报';
  806. }
  807. await ctx.service.financialPayAudit.start(ctx.financialPay.id, ctx.financialPay.times);
  808. ctx.redirect(ctx.request.header.referer);
  809. } catch (err) {
  810. this.log(err);
  811. ctx.session.postError = err.toString();
  812. ctx.redirect(ctx.request.header.referer);
  813. }
  814. }
  815. /**
  816. * 审批
  817. * @param ctx
  818. * @return {Promise<void>}
  819. */
  820. async checkPayAudit(ctx) {
  821. try {
  822. if (!ctx.financialPay || ctx.financialPay.status !== auditConst.financial.status.checking) {
  823. throw '当前资金支付数据有误';
  824. }
  825. if (ctx.financialPay.curAuditorIds.length === 0 || ctx.financialPay.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  826. throw '您无权进行该操作';
  827. }
  828. const data = {
  829. checkType: parseInt(ctx.request.body.checkType),
  830. opinion: ctx.request.body.opinion,
  831. };
  832. if (!data.checkType || isNaN(data.checkType)) {
  833. throw '提交数据错误';
  834. }
  835. await ctx.service.financialPayAudit.check(ctx.financialPay, data);
  836. ctx.redirect(ctx.request.header.referer);
  837. } catch (err) {
  838. this.log(err);
  839. ctx.session.postError = err.toString();
  840. ctx.redirect(ctx.request.header.referer);
  841. }
  842. }
  843. async payDetailSave(ctx) {
  844. try {
  845. const responseData = {
  846. err: 0, msg: '', data: {},
  847. };
  848. const data = JSON.parse(ctx.request.body.data);
  849. if (!data.type) {
  850. throw '提交数据错误';
  851. }
  852. if (data.type !== 'pay_contract_list' && data.type !== 'file_bill') {
  853. if (ctx.financialPay.status !== auditConst.financial.status.uncheck && ctx.financialPay.status !== auditConst.financial.status.checkNo) {
  854. throw '该状态下不允许编辑';
  855. }
  856. if (ctx.financialPay.uid !== ctx.session.sessionUser.accountId) {
  857. throw '非该资金支付填报人无权限编辑';
  858. }
  859. }
  860. switch (data.type) {
  861. case 'pay_save':
  862. responseData.data = await ctx.service.financialPay.savePay(ctx.financialPay.id, data);
  863. break;
  864. case 'pay_contract_list':
  865. responseData.data = await ctx.service.financialPayContract.getContractList(ctx.financialPay.id);
  866. break;
  867. case 'contract_list':
  868. responseData.data.contracts = await ctx.service.contract.getAllDataByCondition({ where: { tid: ctx.financialPay.tid, contract_type: 1 } });
  869. responseData.data.contractTrees = await ctx.service.contractTree.getAllDataByCondition({ where: { tid: ctx.financialPay.tid, contract_type: 1 } });
  870. break;
  871. case 'contract_white_add':
  872. responseData.data = await ctx.service.financialPayContract.addWhiteContract(ctx.financialPay);
  873. break;
  874. case 'contract_add':
  875. responseData.data = await ctx.service.financialPayContract.addContracts(ctx.financialPay, data.contract_ids);
  876. break;
  877. case 'contract_del':
  878. responseData.data = await ctx.service.financialPayContract.delContract(ctx.financialPay.id, data.ids);
  879. break;
  880. case 'contract_update':
  881. responseData.data = await ctx.service.financialPayContract.updateContract(ctx.financialPay.id, data.updateData);
  882. break;
  883. case 'contract_paste':
  884. responseData.data = await ctx.service.financialPayContract.updateContracts(ctx.financialPay.id, data.updateData);
  885. break;
  886. case 'file_bill':
  887. responseData.data = await ctx.service.financialPayAtt.updateBill(data.id, data.bill);
  888. break;
  889. default: throw '参数有误';
  890. }
  891. ctx.body = responseData;
  892. } catch (err) {
  893. this.log(err);
  894. ctx.body = { err: 1, msg: err.toString(), data: {} };
  895. }
  896. }
  897. /**
  898. * 上传附件
  899. * @param {*} ctx 上下文
  900. */
  901. async payUploadFile(ctx) {
  902. let stream;
  903. try {
  904. const parts = this.ctx.multipart({
  905. autoFields: true,
  906. });
  907. const files = [];
  908. const create_time = Date.parse(new Date()) / 1000;
  909. let idx = 0;
  910. // const extra_upload = ctx.financialPay.status === auditConst.status.checked;
  911. while ((stream = await parts()) !== undefined) {
  912. if (!stream.filename) {
  913. // 如果没有传入直接返回
  914. return;
  915. }
  916. const fileInfo = path.parse(stream.filename);
  917. const filepath = `sp/financial/${ctx.subProject.id}/pay/${ctx.financialPay.id}/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  918. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  919. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  920. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  921. ++idx;
  922. stream && (await sendToWormhole(stream));
  923. }
  924. const in_time = new Date();
  925. const type = parts.field.type ? parseInt(parts.field.type) : 0;
  926. const fpcid = parts.field.fpcid ? parseInt(parts.field.fpcid) : null;
  927. const payload = files.map(file => {
  928. let idx;
  929. if (Array.isArray(parts.field.name)) {
  930. idx = parts.field.name.findIndex(name => name === file.name);
  931. } else {
  932. idx = 'isString';
  933. }
  934. const newFile = {
  935. spid: ctx.subProject.id,
  936. fpid: ctx.financialPay.id,
  937. fpcid,
  938. uid: ctx.session.sessionUser.accountId,
  939. filename: file.name,
  940. fileext: file.ext,
  941. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  942. filepath: file.filepath,
  943. upload_time: in_time,
  944. type,
  945. };
  946. return newFile;
  947. });
  948. // 执行文件信息写入数据库
  949. await ctx.service.financialPayAtt.saveFileMsgToDb(payload);
  950. // 将最新的当前标段的所有文件信息返回
  951. const data = await ctx.service.financialPayAtt.getAtt(ctx.financialPay.id, fpcid);
  952. ctx.body = { err: 0, msg: '', data };
  953. } catch (err) {
  954. stream && (await sendToWormhole(stream));
  955. this.log(err);
  956. ctx.body = { err: 1, msg: err.toString(), data: null };
  957. }
  958. }
  959. /**
  960. * 删除附件
  961. * @param {Ojbect} ctx 上下文
  962. */
  963. async payDeleteFile(ctx) {
  964. try {
  965. const { fpcid, id } = JSON.parse(ctx.request.body.data);
  966. const fileInfo = await ctx.service.financialPayAtt.getDataById(id);
  967. if (fileInfo || Object.keys(fileInfo).length) {
  968. // 先删除文件
  969. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  970. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  971. // 再删除数据库
  972. await ctx.service.financialPayAtt.delete(id);
  973. } else {
  974. throw '不存在该文件';
  975. }
  976. const data = await ctx.service.financialPayAtt.getAtt(ctx.financialPay.id, fpcid ? fpcid : null);
  977. ctx.body = { err: 0, msg: '请求成功', data };
  978. } catch (err) {
  979. this.log(err);
  980. ctx.body = { err: 1, msg: err.toString(), data: null };
  981. }
  982. }
  983. /**
  984. * 下载附件
  985. * @param {Object} ctx - egg全局变量
  986. * @return {void}
  987. */
  988. async payDownloadFile(ctx) {
  989. const id = ctx.params.fid;
  990. if (id) {
  991. try {
  992. const fileInfo = await ctx.service.financialPayAtt.getDataById(id);
  993. if (fileInfo !== undefined && fileInfo !== '') {
  994. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  995. // 解决中文无法下载问题
  996. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  997. let disposition = '';
  998. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  999. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  1000. } else if (userAgent.indexOf('firefox') >= 0) {
  1001. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  1002. } else {
  1003. /* safari等其他非主流浏览器只能自求多福了 */
  1004. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  1005. }
  1006. ctx.response.set({
  1007. 'Content-Type': 'application/octet-stream',
  1008. 'Content-Disposition': disposition,
  1009. 'Content-Length': fileInfo.filesize,
  1010. });
  1011. // ctx.body = await fs.createReadStream(fileName);
  1012. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  1013. } else {
  1014. throw '不存在该文件';
  1015. }
  1016. } catch (err) {
  1017. this.log(err);
  1018. this.setMessage(err.toString(), this.messageType.ERROR);
  1019. }
  1020. }
  1021. }
  1022. }
  1023. return FinancialController;
  1024. };