change_controller.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2018/8/14
  7. * @version
  8. */
  9. const moment = require('moment');
  10. const sendToWormhole = require('stream-wormhole');
  11. const fs = require('fs');
  12. const path = require('path');
  13. const audit = require('../const/audit');
  14. const codeRuleConst = require('../const/code_rule');
  15. const changeConst = require('../const/change');
  16. const accountGroup = require('../const/account_group').group;
  17. const shenpiConst = require('../const/shenpi');
  18. // const tenderMenu = require('../../config/menu').tenderMenu;
  19. module.exports = app => {
  20. class ChangeController extends app.BaseController {
  21. /**
  22. * 构造函数
  23. *
  24. * @param {Object} ctx - egg全局变量
  25. * @return {void}
  26. */
  27. constructor(ctx) {
  28. super(ctx);
  29. ctx.showProject = true;
  30. ctx.showTender = true;
  31. ctx.showTitle = true;
  32. }
  33. async _filterChanges(ctx, status = 0) {
  34. const tenderId = ctx.params.id;
  35. ctx.session.sessionUser.tenderId = tenderId;
  36. const tender = await this.service.tender.getDataById(tenderId);
  37. // const tenderList = await this.service.tender.getList();
  38. const page = ctx.page;
  39. const changes = await ctx.service.change.getListByStatus(tender.id, status);
  40. const total = await ctx.service.change.getCountByStatus(tender.id, status);
  41. if (changes !== null) {
  42. let i = 0;
  43. for (const c of changes) {
  44. const status = c.status === audit.flow.status.uncheck ? 0 : 1;
  45. // 根据审批人对当前变更令的状态取不同的展示方式。
  46. let changeAudit = '';
  47. let auditStatus = 0;
  48. switch (c.status) {
  49. case 1:
  50. auditStatus = 1;
  51. break;
  52. case 2:
  53. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  54. auditStatus = changeAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  55. break;
  56. case 3:
  57. case 4:
  58. auditStatus = 0;
  59. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  60. break;
  61. case 5:
  62. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times - 1, status);
  63. auditStatus = c.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  64. break;
  65. case 6:
  66. changeAudit = await ctx.service.changeAudit.getLastBackUser(c.cid, c.times);
  67. const checkingAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  68. auditStatus = checkingAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  69. break;
  70. default:
  71. break;
  72. }
  73. changes[i].changeAudit = changeAudit;
  74. changes[i].auditStatus = auditStatus;
  75. i++;
  76. }
  77. }
  78. // 分页相关
  79. const pageInfo = {
  80. page,
  81. total: Math.ceil(total / app.config.pageSize),
  82. queryData: JSON.stringify(ctx.urlInfo.query),
  83. };
  84. const filter = JSON.parse(JSON.stringify(audit.filter));
  85. filter.count = [];
  86. filter.count[filter.status.pending] = await ctx.service.change.getCountByStatus(tender.id, filter.status.pending);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  87. filter.count[filter.status.uncheck] = await ctx.service.change.getCountByStatus(tender.id, filter.status.uncheck);// await ctx.service.change.checkingDatas(tender.id, ctx.session.sessionUser.accountId);
  88. filter.count[filter.status.checking] = await ctx.service.change.getCountByStatus(tender.id, filter.status.checking);// await ctx.service.change.checkedDatas(tender.id, ctx.session.sessionUser.accountId);
  89. filter.count[filter.status.checked] = await ctx.service.change.getCountByStatus(tender.id, filter.status.checked);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  90. filter.count[filter.status.checkNo] = await ctx.service.change.getCountByStatus(tender.id, filter.status.checkNo);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  91. const codeRule = tender.c_rule ? JSON.parse(tender.c_rule) : [];
  92. for (const rule of codeRule) {
  93. switch (rule.rule_type) {
  94. case codeRuleConst.measure.ruleType.dealCode:
  95. rule.preview = ctx.tender.info.deal_info.dealCode;
  96. break;
  97. case codeRuleConst.measure.ruleType.tenderName:
  98. rule.preview = tender.name;
  99. break;
  100. case codeRuleConst.measure.ruleType.inDate:
  101. rule.preview = moment().format('YYYY');
  102. break;
  103. case codeRuleConst.measure.ruleType.text:
  104. rule.preview = rule.text;
  105. break;
  106. case codeRuleConst.measure.ruleType.addNo:
  107. const s = '0000000000';
  108. rule.preview = s.substr(s.length - rule.format);
  109. break;
  110. default: break;
  111. }
  112. }
  113. const renderData = {
  114. uid: ctx.session.sessionUser.accountId,
  115. moment,
  116. tender,
  117. // tenderList,
  118. pageInfo,
  119. changes,
  120. filter,
  121. status,
  122. codeRule,
  123. dealCode: ctx.tender.info.deal_info.dealCode,
  124. auditConst: audit.flow,
  125. changeConst,
  126. ruleType: codeRuleConst.ruleType.change,
  127. ruleConst: codeRuleConst.measure,
  128. tenderMenu: this.menu.tenderMenu,
  129. preUrl: '/tender/' + tenderId,
  130. tpUnit: ctx.tender.info.decimal.tp,
  131. };
  132. await this.layout('change/index.ejs', renderData, 'change/modal.ejs');
  133. }
  134. /**
  135. * 变更管理 页面 (Get)
  136. *
  137. * @param {Object} ctx - egg全局变量
  138. * @return {void}
  139. */
  140. async index(ctx) {
  141. try {
  142. await this._filterChanges(ctx);
  143. } catch (err) {
  144. this.log(err);
  145. ctx.redirect('/dashboard');
  146. }
  147. }
  148. /**
  149. *
  150. * @param {Object} ctx - egg全局变量
  151. * @return {void}
  152. */
  153. async newCode(ctx) {
  154. const responseData = {
  155. err: 0,
  156. msg: '',
  157. data: '',
  158. };
  159. try {
  160. const tenderId = ctx.params.id;
  161. if (!tenderId) {
  162. throw '当前未打开标段';
  163. }
  164. const tenderData = await ctx.service.tender.getDataById(tenderId);
  165. const cCodeRule = tenderData.c_rule !== null ? JSON.parse(tenderData.c_rule) : [];
  166. const code = [];
  167. for (const rule of cCodeRule) {
  168. switch (rule.rule_type) {
  169. case codeRuleConst.measure.ruleType.dealCode:
  170. code.push(ctx.tender.info.deal_info.dealCode);
  171. break;
  172. case codeRuleConst.measure.ruleType.tenderName:
  173. code.push(tenderData.name);
  174. break;
  175. case codeRuleConst.measure.ruleType.text:
  176. code.push(rule.text);
  177. break;
  178. case codeRuleConst.measure.ruleType.inDate:
  179. code.push(moment().format('YYYY'));
  180. break;
  181. case codeRuleConst.measure.ruleType.addNo:
  182. let s = '0000000000';
  183. const count = rule.start + await ctx.service.change.count({ tid: tenderId });
  184. s = s + count;
  185. code.push(s.substr(s.length - rule.format));
  186. break;
  187. default: break;
  188. }
  189. }
  190. responseData.data = code.join(tenderData.c_connector !== null && tenderData.c_connector !== 3 ? codeRuleConst.measure.connectorString[tenderData.c_connector] : '');
  191. } catch (err) {
  192. responseData.err = 1;
  193. responseData.msg = err;
  194. }
  195. ctx.body = responseData;
  196. }
  197. /**
  198. * 新增变更 (Post)
  199. *
  200. * @param {Object} ctx - egg全局变量
  201. * @return {void}
  202. */
  203. async add(ctx) {
  204. try {
  205. const tenderId = ctx.params.id;
  206. if (!tenderId) {
  207. throw '当前未打开标段';
  208. }
  209. const data = JSON.parse(ctx.request.body.data);
  210. if (!data.code || data.code === '' || !data.name || data.name === '') {
  211. throw '变更令号不能为空';
  212. }
  213. const change = await ctx.service.change.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  214. ctx.body = { err: 0, msg: '', data: change };
  215. } catch (err) {
  216. this.log(err);
  217. ctx.body = { err: 1, msg: err.toString() };
  218. }
  219. }
  220. /**
  221. * 变更管理 状态筛选 页面 (Get)
  222. * @param {Object} ctx - egg全局变量
  223. * @return {void}
  224. */
  225. async status(ctx) {
  226. try {
  227. const status = parseInt(ctx.params.status);
  228. await this._filterChanges(ctx, status);
  229. } catch (err) {
  230. this.logger.error(err);
  231. ctx.redirect('/tender/' + ctx.params.id + '/change');
  232. }
  233. }
  234. /**
  235. * 变更信息 页面 (Get)
  236. *
  237. * @param {Object} ctx - egg全局变量
  238. * @return {void}
  239. */
  240. async info(ctx) {
  241. try {
  242. const whiteList = this.ctx.app.config.multipart.whitelist;
  243. const tenderid = ctx.params.id !== undefined ? ctx.params.id : ctx.session.sessionUser.tenderId;
  244. ctx.session.sessionUser.tenderId = tenderid;
  245. const tender = await ctx.service.tender.getDataById(tenderid);
  246. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  247. // 后台判断当前人查看info状态
  248. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  249. // 获取附件列表
  250. const attList = await ctx.service.changeAtt.getChangeAttachment(ctx.params.cid);
  251. // 获取其他变更令数据
  252. const othersChange = await ctx.service.change.getOthersChange(ctx.params.id, ctx.params.cid);
  253. // 根据auditStatus获取审批人列表
  254. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  255. // 获取已选清单
  256. let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  257. // 获取用户人验证手机号
  258. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  259. const auth_mobile = pa.auth_mobile;
  260. const renderData = {
  261. uid: ctx.session.sessionUser.accountId,
  262. tender,
  263. change,
  264. othersChange,
  265. changeConst,
  266. auditStatus,
  267. auditConst: audit.flow,
  268. ledgerConsts: audit.ledger.status,
  269. attList,
  270. whiteList,
  271. auditList,
  272. changeList,
  273. tpUnit: ctx.tender.info.decimal.tp,
  274. upUnit: ctx.tender.info.decimal.up,
  275. authMobile: auth_mobile,
  276. shenpiConst,
  277. };
  278. // 根据auditStatus状态获取的不同的数据
  279. if (auditStatus === 1 || auditStatus === 2) {
  280. renderData.changeUnits = changeConst.units;
  281. renderData.precision = ctx.tender.info.precision;
  282. // renderData.accountGroup = accountGroup;
  283. // 获取所有项目参与者
  284. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  285. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  286. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  287. });
  288. renderData.accountList = accountList;
  289. renderData.accountGroup = accountGroup.map((item, idx) => {
  290. const groupList = accountList.filter(item => item.account_group === idx);
  291. return { groupName: item, groupList };
  292. });
  293. // 重新上报获取审批流程
  294. if (auditStatus === 2) {
  295. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  296. // 展示页右侧审批流程列表
  297. const auditList3 = [];
  298. for (let time = 1; time <= change.times - 1; time++) {
  299. const auditTimeList = [];
  300. let max_sort = 1;
  301. for (const al of auditList2) {
  302. if (al.times === time) {
  303. auditTimeList.push(al);
  304. if (al.usite > max_sort) {
  305. max_sort = al.usite;
  306. }
  307. }
  308. }
  309. for (const i in auditTimeList) {
  310. auditTimeList[i].max_sort = max_sort;
  311. }
  312. auditList3.push(auditTimeList);
  313. }
  314. renderData.auditList3 = auditList3;
  315. }
  316. // 根据清单获取提交数据和计算总金额
  317. const changeListData = [];
  318. const changeWhiteListData = [];
  319. let ototalCost = 0;
  320. let ctotalCost = 0;
  321. for (const cl of changeList) {
  322. const cLArray = [
  323. cl.code,
  324. cl.name,
  325. cl.bwmx,
  326. cl.unit,
  327. cl.unit_price,
  328. cl.oamount,
  329. cl.camount,
  330. cl.detail,
  331. cl.lid,
  332. cl.xmj_code,
  333. cl.xmj_jldy,
  334. ];
  335. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, ctx.tender.info.decimal.tp);
  336. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, ctx.tender.info.decimal.tp);
  337. if (cl.lid !== '0') {
  338. changeListData.push(cLArray.join('*;*'));
  339. } else {
  340. changeWhiteListData.push(cLArray.join('*;*'));
  341. }
  342. }
  343. renderData.changeListData = changeListData.join('^_^');
  344. renderData.changeWhiteListData = changeWhiteListData.join('^_^');
  345. renderData.ototalCost = ototalCost;
  346. renderData.ctotalCost = ctotalCost;
  347. // 获取公司列表
  348. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: tenderid } });
  349. renderData.companyList = companyList;
  350. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7) {
  351. // 展示页左侧审批流程列表和清单审批列表数据
  352. const times = change.status === audit.flow.status.back ?
  353. change.times - 1 : change.times;
  354. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  355. // 展示页右侧审批流程列表
  356. const auditList3 = [];
  357. for (let time = 1; time <= times; time++) {
  358. const auditTimeList = [];
  359. let max_sort = 1;
  360. for (const al of auditList) {
  361. if (al.times === time) {
  362. auditTimeList.push(al);
  363. if (al.usite > max_sort) {
  364. max_sort = al.usite;
  365. }
  366. }
  367. }
  368. for (const i in auditTimeList) {
  369. auditTimeList[i].max_sort = max_sort;
  370. }
  371. auditList3.push(auditTimeList);
  372. }
  373. renderData.auditList3 = auditList3;
  374. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  375. renderData.changeList = changeList;
  376. let ototalCost = 0;
  377. let ctotalCost = 0;
  378. let stotalCost = 0;
  379. const auditTotalCost = [];
  380. for (const cl of changeList) {
  381. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  382. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  383. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  384. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  385. // stotalCost += cl.samount !== '' && cl.unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.samount), renderData.tpUnit)) : 0;
  386. stotalCost += cl.samount !== '' && cl.unit_price !== null ? ctx.helper.mul(cl.unit_price, cl.samount, renderData.tpUnit) : 0;
  387. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  388. auditTotalCost.push(audit_amount);
  389. }
  390. renderData.ototalCost = ototalCost;
  391. renderData.ctotalCost = ctotalCost;
  392. renderData.stotalCost = stotalCost;
  393. // 清单表页赋值
  394. for (const [index, au] of auditList2.entries()) {
  395. if (au.usite !== 0) {
  396. au.list_amount = [];
  397. au.totalCost = 0;
  398. for (const [auindex, at] of auditTotalCost.entries()) {
  399. au.list_amount.push(at[index - 1]);
  400. // au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 1]), renderData.tpUnit)) : 0;
  401. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  402. }
  403. }
  404. }
  405. renderData.auditList2 = auditList2;
  406. } else if (auditStatus === 6) {
  407. // 展示页左侧审批流程列表和清单审批列表数据
  408. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  409. renderData.auditList2 = auditList2;
  410. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  411. for (const i in auditList3) {
  412. auditList3[i].max_sort = auditList2.length - 1;
  413. }
  414. renderData.auditList3 = auditList3;
  415. // 展示页右侧审批流程列表
  416. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  417. const auditList4 = [];
  418. for (let time = 1; time <= change.times; time++) {
  419. const auditTimeList = [];
  420. let max_sort = 1;
  421. for (const al of auditList5) {
  422. if (al.times === time) {
  423. auditTimeList.push(al);
  424. if (al.usite > max_sort) {
  425. max_sort = al.usite;
  426. }
  427. }
  428. }
  429. for (const i in auditTimeList) {
  430. auditTimeList[i].max_sort = max_sort;
  431. }
  432. if (auditTimeList.length > 0) {
  433. auditList4.push(auditTimeList);
  434. }
  435. }
  436. renderData.auditList4 = auditList4;
  437. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  438. renderData.changeList = changeList;
  439. let ototalCost = 0;
  440. let ctotalCost = 0;
  441. const auditTotalCost = [];
  442. const auditUnit = [];
  443. for (const cl of changeList) {
  444. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  445. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  446. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  447. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  448. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  449. auditTotalCost.push(audit_amount);
  450. }
  451. renderData.ototalCost = ototalCost;
  452. renderData.ctotalCost = ctotalCost;
  453. // 清单表页赋值
  454. for (const [index, au] of auditList.entries()) {
  455. if (au.usite !== 0) {
  456. au.list_amount = [];
  457. au.totalCost = 0;
  458. if (au.uid === renderData.uid) {
  459. for (const [auindex, at] of auditTotalCost.entries()) {
  460. // if (at[index - 2] !== undefined) {
  461. // au.list_amount.push(at[index - 2]);
  462. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 2]), renderData.tpUnit));
  463. // } else if (at[index - 2] === undefined) {
  464. // au.list_amount.push(changeList[auindex].camount);
  465. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].camount), renderData.tpUnit));
  466. // }
  467. au.list_amount.push(changeList[auindex].spamount);
  468. // au.totalCost += changeList[auindex].unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].spamount), renderData.tpUnit));
  469. au.totalCost += changeList[auindex].unit_price === null ? 0 : ctx.helper.mul(changeList[auindex].unit_price, changeList[auindex].spamount, renderData.tpUnit);
  470. }
  471. } else {
  472. for (const [auindex, at] of auditTotalCost.entries()) {
  473. au.list_amount.push(at[index - 1]);
  474. // au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 1]), renderData.tpUnit)) : 0;
  475. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  476. }
  477. }
  478. }
  479. }
  480. }
  481. renderData.auditList = auditList;
  482. // 获取是否已存在调用变更令
  483. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  484. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  485. await this.layout('change/info.ejs', renderData, 'change/info_modal.ejs');
  486. } catch (err) {
  487. this.log(err);
  488. ctx.redirect('/tender/' + ctx.params.id + '/change');
  489. }
  490. }
  491. async defaultBills(ctx) {
  492. try {
  493. const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  494. const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  495. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  496. ctx.body = { err: 0, msg: '', data: { bills: ledgerData, pos: posData, dealBills } };
  497. } catch (err) {
  498. this.log(err);
  499. ctx.body = { err: 1, msg: err.toString(), data: [] };
  500. }
  501. }
  502. /**
  503. * 变更令上报和保存
  504. * @param {Object} ctx - egg全局变量
  505. * @return {void}
  506. */
  507. async save(ctx) {
  508. // 变更令信息
  509. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  510. try {
  511. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  512. if (!result) {
  513. throw '上报失败';
  514. }
  515. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  516. ctx.body = { err: 0, msg: '保存成功' };
  517. } else {
  518. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  519. }
  520. } catch (err) {
  521. this.log(err);
  522. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  523. ctx.body = { err: 1, msg: err.toString() };
  524. } else {
  525. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  526. }
  527. }
  528. }
  529. /**
  530. * 变更令审批
  531. * @param {Object} ctx - egg全局变量
  532. * @return {void}
  533. */
  534. async approval(ctx) {
  535. try {
  536. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.change_id });
  537. if (!changeData) {
  538. throw '变更令数据错误';
  539. }
  540. const status = parseInt(ctx.request.body.status);
  541. let result = false;
  542. const pid = this.ctx.session.sessionProject.id;
  543. switch (status) {
  544. case 3:// 审批通过
  545. result = await ctx.service.change.approvalSuccess(pid, ctx.request.body, changeData);
  546. break;
  547. case 4:// 审批终止
  548. result = await ctx.service.change.approvalStop(ctx.request.body);
  549. break;
  550. case 5:// 审批退回到原报人
  551. result = await ctx.service.change.approvalBack(pid, ctx.request.body, changeData);
  552. break;
  553. case 6:// 审批退回到上一个审批人
  554. result = await ctx.service.change.approvalBackNew(pid, ctx.request.body, changeData);
  555. break;
  556. default:break;
  557. }
  558. if (!result) {
  559. throw '审批失败';
  560. }
  561. ctx.redirect(ctx.request.header.referer);
  562. } catch (err) {
  563. console.log(err);
  564. ctx.redirect(ctx.request.header.referer);
  565. }
  566. }
  567. /**
  568. * 变更公司管理
  569. * @param {Object} ctx - egg全局变量
  570. * @return {void}
  571. */
  572. async updateCompany(ctx) {
  573. const responseData = {
  574. err: 0,
  575. msg: '',
  576. data: '',
  577. };
  578. try {
  579. const data = JSON.parse(ctx.request.body.data);
  580. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  581. throw '参数有误';
  582. }
  583. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  584. responseData.data = { add: addCompany, select: selectCompany };
  585. } catch (err) {
  586. responseData.err = 1;
  587. responseData.msg = err;
  588. }
  589. ctx.body = responseData;
  590. }
  591. /**
  592. * 上传附件
  593. * @param {Object} ctx - egg全局变量
  594. * @return {void}
  595. */
  596. async uploadFile(ctx) {
  597. const responseData = {
  598. err: 0,
  599. msg: '',
  600. data: [],
  601. };
  602. let stream;
  603. try {
  604. const parts = ctx.multipart({ autoFields: true });
  605. const files = [];
  606. let index = 0;
  607. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  608. const extra_upload = change.status === audit.flow.status.checked;
  609. while ((stream = await parts()) !== undefined) {
  610. // 判断用户是否选择上传文件
  611. if (!stream.filename) {
  612. throw '请选择上传的文件!';
  613. }
  614. // const create_time = Date.parse(new Date()) / 1000;
  615. // const fileInfo = path.parse(stream.filename);
  616. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  617. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  618. // // 判断文件夹是否存在,不存在则直接创建文件夹
  619. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  620. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  621. // }
  622. // // 保存文件
  623. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  624. const fileInfo = path.parse(stream.filename);
  625. const create_time = Date.parse(new Date()) / 1000;
  626. const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  627. await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  628. await sendToWormhole(stream);
  629. // 保存数据到att表
  630. const fileData = {
  631. in_time: create_time,
  632. filename: fileInfo.name,
  633. fileext: fileInfo.ext,
  634. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  635. filepath,
  636. extra_upload,
  637. };
  638. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  639. if (!result) {
  640. throw '导入数据库保存失败';
  641. }
  642. fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  643. fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  644. fileData.id = result.insertId;
  645. delete fileData.filepath;
  646. files.push(fileData);
  647. ++index;
  648. }
  649. responseData.data = files;
  650. } catch (err) {
  651. this.log(err);
  652. // 失败需要消耗掉stream 以防卡死
  653. if (stream) {
  654. await sendToWormhole(stream);
  655. }
  656. this.setMessage(err.toString(), this.messageType.ERROR);
  657. }
  658. ctx.body = responseData;
  659. }
  660. /**
  661. * 下载附件
  662. * @param {Object} ctx - egg全局变量
  663. * @return {void}
  664. */
  665. async downloadFile(ctx) {
  666. const id = ctx.params.id;
  667. if (id) {
  668. try {
  669. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  670. if (fileInfo !== undefined && fileInfo !== '') {
  671. const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  672. // 解决中文无法下载问题
  673. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  674. let disposition = '';
  675. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  676. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  677. } else if (userAgent.indexOf('firefox') >= 0) {
  678. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  679. } else {
  680. /* safari等其他非主流浏览器只能自求多福了 */
  681. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  682. }
  683. ctx.response.set({
  684. 'Content-Type': 'application/octet-stream',
  685. 'Content-Disposition': disposition,
  686. 'Content-Length': fileInfo.filesize,
  687. });
  688. ctx.body = await fs.createReadStream(fileName);
  689. } else {
  690. throw '不存在该文件';
  691. }
  692. } catch (err) {
  693. this.log(err);
  694. this.setMessage(err.toString(), this.messageType.ERROR);
  695. }
  696. }
  697. }
  698. /**
  699. * 批量下载 - 压缩成zip文件返回
  700. * @param {Oject} ctx - 全局上下文
  701. */
  702. async downloadZip(ctx) {
  703. try {
  704. const fileIds = JSON.parse(ctx.request.query.fileIds);
  705. // const { fileIds } = JSON.parse(ctx.request.body.data);
  706. // console.log('fileIds', fileIds);
  707. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  708. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  709. const time = Date.now();
  710. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  711. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  712. // 解决中文无法下载问题
  713. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  714. let disposition = '';
  715. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  716. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  717. } else if (userAgent.indexOf('firefox') >= 0) {
  718. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  719. } else {
  720. /* safari等其他非主流浏览器只能自求多福了 */
  721. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  722. }
  723. ctx.response.set({
  724. 'Content-Type': 'application/octet-stream',
  725. 'Content-Disposition': disposition,
  726. 'Content-Length': size,
  727. });
  728. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  729. ctx.body = readStream;
  730. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  731. readStream.on('close', () => {
  732. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  733. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  734. }
  735. });
  736. } catch (error) {
  737. this.log(error);
  738. }
  739. }
  740. /**
  741. * 删除附件
  742. * @param {Object} ctx - egg全局变量
  743. * @return {void}
  744. */
  745. async deleteFile(ctx) {
  746. const responseData = {
  747. err: 0,
  748. msg: '',
  749. data: '',
  750. };
  751. try {
  752. const data = JSON.parse(ctx.request.body.data);
  753. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  754. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  755. if (!fileInfo || !Object.keys(fileInfo).length) {
  756. throw '该文件不存在';
  757. }
  758. if (!fileInfo.extra_upload && change.status === audit.flow.status.checked) {
  759. throw '无权限删除';
  760. }
  761. if (fileInfo !== undefined && fileInfo !== '') {
  762. // 先删除文件
  763. await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  764. // 再删除数据库
  765. await ctx.service.changeAtt.deleteById(data.id);
  766. responseData.data = '';
  767. } else {
  768. throw '不存在该文件';
  769. }
  770. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  771. // throw '参数有误';
  772. // }
  773. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  774. // responseData.data = { add: addCompany, select: selectCompany };
  775. } catch (err) {
  776. responseData.err = 1;
  777. responseData.msg = err;
  778. }
  779. ctx.body = responseData;
  780. }
  781. /**
  782. * 查看附件
  783. * @param {Object} ctx - egg全局变量
  784. * @return {void}
  785. */
  786. async checkFile(ctx) {
  787. const responseData = { err: 0, msg: '' };
  788. const id = parseInt(ctx.params.id);
  789. if (id) {
  790. try {
  791. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  792. if (fileInfo && Object.keys(fileInfo).length) {
  793. let filepath = fileInfo.filepath;
  794. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  795. filepath = `/change/download/file/${fileInfo.id}`;
  796. } else {
  797. filepath = filepath.replace(/^app|\/app/, '');
  798. }
  799. fileInfo.filepath && (responseData.data = { filepath });
  800. }
  801. } catch (error) {
  802. this.log(error);
  803. this.setMessage(error.toString(), this.messageType.ERROR);
  804. responseData.err = 1;
  805. responseData.msg = error.toString();
  806. }
  807. }
  808. ctx.body = responseData;
  809. }
  810. /**
  811. * 删除变更令
  812. * @param {Object} ctx - egg全局变量
  813. * @return {void}
  814. */
  815. async delete(ctx) {
  816. try {
  817. const result = await ctx.service.change.delete(ctx.request.body.cid);
  818. if (!result) {
  819. throw '删除变更令失败';
  820. }
  821. ctx.redirect(ctx.request.header.referer);
  822. } catch (err) {
  823. console.log(err);
  824. ctx.redirect(ctx.request.header.referer);
  825. }
  826. }
  827. /**
  828. * 变更令重新审批
  829. * @param {Object} ctx - egg全局变量
  830. * @return {void}
  831. */
  832. async checkAgain(ctx) {
  833. try {
  834. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  835. if (!changeData) {
  836. throw '变更令数据错误';
  837. }
  838. // 获取终审
  839. const auditInfo = (await this.ctx.service.changeAudit.getAllDataByCondition({ where: { cid: changeData.cid }, orders: [['usort', 'desc']], limit: 1, offset: 0 }))[0];
  840. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== auditInfo.uid) {
  841. throw '您无权进行该操作';
  842. }
  843. if (ctx.session.sessionUser.loginStatus === 0) {
  844. const code = ctx.request.body.code;
  845. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  846. if (!pa.auth_mobile) {
  847. throw '未绑定手机号';
  848. }
  849. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  850. const cacheCode = await app.redis.get(cacheKey);
  851. // console.log(cacheCode);
  852. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  853. throw '验证码不正确!';
  854. }
  855. }
  856. // 重新审批
  857. const result = await ctx.service.change.checkAgain(changeData.cid);
  858. if (!result) {
  859. throw '重新审批失败';
  860. }
  861. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  862. ctx.body = {
  863. err: 0,
  864. url: ctx.request.header.referer,
  865. msg: '',
  866. };
  867. } catch (err) {
  868. console.log(err);
  869. // ctx.redirect(ctx.request.header.referer);
  870. ctx.body = {
  871. err: 1,
  872. // url: ctx.request.header.referer,
  873. msg: err,
  874. };
  875. }
  876. }
  877. /**
  878. * 获取变更清单
  879. * @param ctx
  880. * @return {Promise<void>}
  881. */
  882. async bills(ctx) {
  883. try {
  884. const data = JSON.parse(ctx.request.body.data);
  885. const responseData = { err: 0, msg: '', data: [] };
  886. switch (data.type) {
  887. case 'gather':
  888. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  889. break;
  890. default:
  891. throw '查询的数据不存在';
  892. }
  893. ctx.body = responseData;
  894. } catch (err) {
  895. this.log(err);
  896. this.ajaxErrorBody(err, '获取变更清单失败');
  897. }
  898. }
  899. /**
  900. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  901. * @param ctx
  902. * @return {Promise<void>}
  903. */
  904. async checkCodeRepeat(ctx) {
  905. const responseData = {
  906. err: 0,
  907. msg: '',
  908. data: '',
  909. };
  910. try {
  911. const tenderId = ctx.params.id;
  912. const cid = ctx.params.cid;
  913. const data = JSON.parse(ctx.request.body.data);
  914. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  915. if (result) {
  916. throw '该变更令号(批复编号)已使用';
  917. }
  918. } catch (err) {
  919. responseData.err = 1;
  920. responseData.msg = err;
  921. }
  922. ctx.body = responseData;
  923. }
  924. /**
  925. * 拷贝其他变更令
  926. * @param {object} ctx - 全局上下文
  927. */
  928. async copyChange(ctx) {
  929. const responseData = {
  930. err: 0,
  931. msg: '',
  932. data: '',
  933. };
  934. try {
  935. const cid = ctx.params.cid;
  936. const copy_cid = JSON.parse(ctx.request.body.data);
  937. const result = await ctx.service.change.handleCopyChange(cid, copy_cid);
  938. if (!result) {
  939. responseData.err = 1;
  940. responseData.msg = '拷贝失败!';
  941. }
  942. } catch (error) {
  943. responseData.err = 1;
  944. responseData.msg = error;
  945. }
  946. ctx.body = responseData;
  947. }
  948. }
  949. return ChangeController;
  950. };