change_controller.js 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  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. cl.gcl_id,
  335. ];
  336. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, ctx.tender.info.decimal.tp);
  337. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, ctx.tender.info.decimal.tp);
  338. if (cl.lid !== '0') {
  339. changeListData.push(cLArray.join('*;*'));
  340. } else {
  341. changeWhiteListData.push(cLArray.join('*;*'));
  342. }
  343. }
  344. renderData.changeListData = changeListData.join('^_^');
  345. renderData.changeWhiteListData = changeWhiteListData.join('^_^');
  346. renderData.ototalCost = ototalCost;
  347. renderData.ctotalCost = ctotalCost;
  348. // 获取公司列表
  349. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: tenderid } });
  350. renderData.companyList = companyList;
  351. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7) {
  352. // 展示页左侧审批流程列表和清单审批列表数据
  353. const times = change.status === audit.flow.status.back ?
  354. change.times - 1 : change.times;
  355. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  356. // 展示页右侧审批流程列表
  357. const auditList3 = [];
  358. for (let time = 1; time <= times; time++) {
  359. const auditTimeList = [];
  360. let max_sort = 1;
  361. for (const al of auditList) {
  362. if (al.times === time) {
  363. auditTimeList.push(al);
  364. if (al.usite > max_sort) {
  365. max_sort = al.usite;
  366. }
  367. }
  368. }
  369. for (const i in auditTimeList) {
  370. auditTimeList[i].max_sort = max_sort;
  371. }
  372. auditList3.push(auditTimeList);
  373. }
  374. renderData.auditList3 = auditList3;
  375. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  376. renderData.changeList = changeList;
  377. let ototalCost = 0;
  378. let ctotalCost = 0;
  379. let stotalCost = 0;
  380. const auditTotalCost = [];
  381. for (const cl of changeList) {
  382. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  383. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  384. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  385. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  386. // stotalCost += cl.samount !== '' && cl.unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.samount), renderData.tpUnit)) : 0;
  387. stotalCost += cl.samount !== '' && cl.unit_price !== null ? ctx.helper.mul(cl.unit_price, cl.samount, renderData.tpUnit) : 0;
  388. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  389. auditTotalCost.push(audit_amount);
  390. }
  391. renderData.ototalCost = ototalCost;
  392. renderData.ctotalCost = ctotalCost;
  393. renderData.stotalCost = stotalCost;
  394. // 清单表页赋值
  395. for (const [index, au] of auditList2.entries()) {
  396. if (au.usite !== 0) {
  397. au.list_amount = [];
  398. au.totalCost = 0;
  399. for (const [auindex, at] of auditTotalCost.entries()) {
  400. au.list_amount.push(at[index - 1]);
  401. // 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;
  402. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  403. }
  404. }
  405. }
  406. renderData.auditList2 = auditList2;
  407. } else if (auditStatus === 6) {
  408. // 展示页左侧审批流程列表和清单审批列表数据
  409. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  410. renderData.auditList2 = auditList2;
  411. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  412. for (const i in auditList3) {
  413. auditList3[i].max_sort = auditList2.length - 1;
  414. }
  415. renderData.auditList3 = auditList3;
  416. // 展示页右侧审批流程列表
  417. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  418. const auditList4 = [];
  419. for (let time = 1; time <= change.times; time++) {
  420. const auditTimeList = [];
  421. let max_sort = 1;
  422. for (const al of auditList5) {
  423. if (al.times === time) {
  424. auditTimeList.push(al);
  425. if (al.usite > max_sort) {
  426. max_sort = al.usite;
  427. }
  428. }
  429. }
  430. for (const i in auditTimeList) {
  431. auditTimeList[i].max_sort = max_sort;
  432. }
  433. if (auditTimeList.length > 0) {
  434. auditList4.push(auditTimeList);
  435. }
  436. }
  437. renderData.auditList4 = auditList4;
  438. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  439. renderData.changeList = changeList;
  440. let ototalCost = 0;
  441. let ctotalCost = 0;
  442. const auditTotalCost = [];
  443. const auditUnit = [];
  444. for (const cl of changeList) {
  445. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  446. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  447. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  448. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  449. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  450. auditTotalCost.push(audit_amount);
  451. }
  452. renderData.ototalCost = ototalCost;
  453. renderData.ctotalCost = ctotalCost;
  454. // 清单表页赋值
  455. for (const [index, au] of auditList.entries()) {
  456. if (au.usite !== 0) {
  457. au.list_amount = [];
  458. au.totalCost = 0;
  459. if (au.uid === renderData.uid) {
  460. for (const [auindex, at] of auditTotalCost.entries()) {
  461. // if (at[index - 2] !== undefined) {
  462. // au.list_amount.push(at[index - 2]);
  463. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 2]), renderData.tpUnit));
  464. // } else if (at[index - 2] === undefined) {
  465. // au.list_amount.push(changeList[auindex].camount);
  466. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].camount), renderData.tpUnit));
  467. // }
  468. au.list_amount.push(changeList[auindex].spamount);
  469. // au.totalCost += changeList[auindex].unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].spamount), renderData.tpUnit));
  470. au.totalCost += changeList[auindex].unit_price === null ? 0 : ctx.helper.mul(changeList[auindex].unit_price, changeList[auindex].spamount, renderData.tpUnit);
  471. }
  472. } else {
  473. for (const [auindex, at] of auditTotalCost.entries()) {
  474. au.list_amount.push(at[index - 1]);
  475. // 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;
  476. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  477. }
  478. }
  479. }
  480. }
  481. }
  482. renderData.auditList = auditList;
  483. // 获取是否已存在调用变更令
  484. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  485. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  486. await this.layout('change/info.ejs', renderData, 'change/info_modal.ejs');
  487. } catch (err) {
  488. this.log(err);
  489. ctx.redirect('/tender/' + ctx.params.id + '/change');
  490. }
  491. }
  492. /**
  493. * 变更信息 新版本页面 (Get)
  494. *
  495. * @param {Object} ctx - egg全局变量
  496. * @return {void}
  497. */
  498. async information(ctx) {
  499. try {
  500. const whiteList = this.ctx.app.config.multipart.whitelist;
  501. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  502. const change = ctx.change;
  503. // 后台判断当前人查看info状态
  504. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  505. // 获取附件列表
  506. const attList = await ctx.service.changeAtt.getChangeAttachment(change.cid);
  507. // 获取其他变更令数据
  508. const othersChange = await ctx.service.change.getOthersChange(ctx.tender.id, change.cid);
  509. // 根据auditStatus获取审批人列表
  510. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  511. // 获取已选清单
  512. let changeList = await ctx.service.changeAuditList.getAllDataByCondition({
  513. where: { cid: change.cid },
  514. orders: [['lid', 'desc'], ['id', 'asc']],
  515. });
  516. // 获取用户人验证手机号
  517. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  518. const auth_mobile = pa.auth_mobile;
  519. const renderData = {
  520. tender,
  521. change,
  522. othersChange,
  523. changeConst,
  524. auditStatus,
  525. auditConst: audit.flow,
  526. ledgerConsts: audit.ledger.status,
  527. attList,
  528. whiteList,
  529. auditList,
  530. changeList,
  531. tpUnit: ctx.tender.info.decimal.tp,
  532. upUnit: ctx.tender.info.decimal.up,
  533. authMobile: auth_mobile,
  534. shenpiConst,
  535. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.information),
  536. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  537. precision: ctx.tender.info.precision,
  538. };
  539. // 根据auditStatus状态获取的不同的数据
  540. if (auditStatus === 1 || auditStatus === 2) {
  541. renderData.changeUnits = changeConst.units;
  542. // renderData.accountGroup = accountGroup;
  543. // 获取所有项目参与者
  544. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  545. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  546. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  547. });
  548. renderData.accountList = accountList;
  549. renderData.accountGroup = accountGroup.map((item, idx) => {
  550. const groupList = accountList.filter(item => item.account_group === idx);
  551. return { groupName: item, groupList };
  552. });
  553. // 重新上报获取审批流程
  554. if (auditStatus === 2) {
  555. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  556. // 展示页右侧审批流程列表
  557. const auditList3 = [];
  558. for (let time = 1; time <= change.times - 1; time++) {
  559. const auditTimeList = [];
  560. let max_sort = 1;
  561. for (const al of auditList2) {
  562. if (al.times === time) {
  563. auditTimeList.push(al);
  564. if (al.usite > max_sort) {
  565. max_sort = al.usite;
  566. }
  567. }
  568. }
  569. for (const i in auditTimeList) {
  570. auditTimeList[i].max_sort = max_sort;
  571. }
  572. auditList3.push(auditTimeList);
  573. }
  574. renderData.auditList3 = auditList3;
  575. }
  576. // 获取公司列表
  577. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  578. renderData.companyList = companyList;
  579. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7) {
  580. // 展示页左侧审批流程列表和清单审批列表数据
  581. const times = change.status === audit.flow.status.back ?
  582. change.times - 1 : change.times;
  583. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  584. // 展示页右侧审批流程列表
  585. const auditList3 = [];
  586. for (let time = 1; time <= times; time++) {
  587. const auditTimeList = [];
  588. let max_sort = 1;
  589. for (const al of auditList) {
  590. if (al.times === time) {
  591. auditTimeList.push(al);
  592. if (al.usite > max_sort) {
  593. max_sort = al.usite;
  594. }
  595. }
  596. }
  597. for (const i in auditTimeList) {
  598. auditTimeList[i].max_sort = max_sort;
  599. }
  600. auditList3.push(auditTimeList);
  601. }
  602. renderData.auditList3 = auditList3;
  603. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  604. for (const cl of changeList) {
  605. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  606. // 清单表页赋值
  607. for (const [index, au] of auditList2.entries()) {
  608. if (au.usite !== 0) {
  609. cl['audit_amount_' + au.uid] = audit_amount[index] ? audit_amount[index] : null;
  610. }
  611. }
  612. }
  613. renderData.changeList = changeList;
  614. renderData.auditList2 = auditList2;
  615. } else if (auditStatus === 6) {
  616. // 展示页左侧审批流程列表和清单审批列表数据
  617. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  618. renderData.auditList2 = auditList2;
  619. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  620. for (const i in auditList3) {
  621. auditList3[i].max_sort = auditList2.length - 1;
  622. }
  623. renderData.auditList3 = auditList3;
  624. // 展示页右侧审批流程列表
  625. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  626. const auditList4 = [];
  627. for (let time = 1; time <= change.times; time++) {
  628. const auditTimeList = [];
  629. let max_sort = 1;
  630. for (const al of auditList5) {
  631. if (al.times === time) {
  632. auditTimeList.push(al);
  633. if (al.usite > max_sort) {
  634. max_sort = al.usite;
  635. }
  636. }
  637. }
  638. for (const i in auditTimeList) {
  639. auditTimeList[i].max_sort = max_sort;
  640. }
  641. if (auditTimeList.length > 0) {
  642. auditList4.push(auditTimeList);
  643. }
  644. }
  645. renderData.auditList4 = auditList4;
  646. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  647. renderData.changeList = changeList;
  648. let ototalCost = 0;
  649. let ctotalCost = 0;
  650. const auditTotalCost = [];
  651. const auditUnit = [];
  652. for (const cl of changeList) {
  653. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  654. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  655. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  656. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  657. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  658. auditTotalCost.push(audit_amount);
  659. }
  660. renderData.ototalCost = ototalCost;
  661. renderData.ctotalCost = ctotalCost;
  662. // 清单表页赋值
  663. for (const [index, au] of auditList.entries()) {
  664. if (au.usite !== 0) {
  665. au.list_amount = [];
  666. au.totalCost = 0;
  667. if (au.uid === renderData.uid) {
  668. for (const [auindex, at] of auditTotalCost.entries()) {
  669. // if (at[index - 2] !== undefined) {
  670. // au.list_amount.push(at[index - 2]);
  671. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 2]), renderData.tpUnit));
  672. // } else if (at[index - 2] === undefined) {
  673. // au.list_amount.push(changeList[auindex].camount);
  674. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].camount), renderData.tpUnit));
  675. // }
  676. au.list_amount.push(changeList[auindex].spamount);
  677. // au.totalCost += changeList[auindex].unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].spamount), renderData.tpUnit));
  678. au.totalCost += changeList[auindex].unit_price === null ? 0 : ctx.helper.mul(changeList[auindex].unit_price, changeList[auindex].spamount, renderData.tpUnit);
  679. }
  680. } else {
  681. for (const [auindex, at] of auditTotalCost.entries()) {
  682. au.list_amount.push(at[index - 1]);
  683. // 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;
  684. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  685. }
  686. }
  687. }
  688. }
  689. }
  690. renderData.auditList = auditList;
  691. // 获取是否已存在调用变更令
  692. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  693. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  694. await this.layout('change/information.ejs', renderData, 'change/information_modal.ejs');
  695. } catch (err) {
  696. this.log(err);
  697. ctx.redirect('/tender/' + ctx.params.id + '/change');
  698. }
  699. }
  700. /**
  701. * 变更清单 - 操作 (Ajax)
  702. * @param ctx
  703. * @return {Promise<void>}
  704. */
  705. async saveListsData(ctx) {
  706. try {
  707. const data = JSON.parse(ctx.request.body.data);
  708. const responseData = {
  709. err: 0,
  710. msg: '',
  711. data: {},
  712. };
  713. switch (data.type) {
  714. case 'add':
  715. responseData.data = await ctx.service.changeAuditList.add(data.postData);
  716. break;
  717. case 'del':
  718. await ctx.service.changeAuditList.del(data.id);
  719. break;
  720. case 'update':
  721. await ctx.service.changeAuditList.save(data.updateData);
  722. break;
  723. case 'paste':
  724. await ctx.service.changeAuditList.saveDatas(data.updateData);
  725. // 取所有工料表
  726. responseData.data = await ctx.service.changeAuditList.getAllDataByCondition({
  727. where: { cid: ctx.change.cid },
  728. orders: [['lid', 'desc'], ['id', 'asc']],
  729. });
  730. break;
  731. case 'ledger_list':
  732. await ctx.service.changeAuditList.saveLedgerListDatas(data.updateData);
  733. // 取所有工料表
  734. responseData.data = await ctx.service.changeAuditList.getAllDataByCondition({
  735. where: { cid: ctx.change.cid },
  736. orders: [['lid', 'desc'], ['id', 'asc']],
  737. });
  738. break;
  739. case 'info':
  740. await ctx.service.change.saveInfo(data.updateData);
  741. // 取所有工料表
  742. responseData.data = '保存成功';
  743. break;
  744. default: throw '参数有误';
  745. }
  746. ctx.body = responseData;
  747. } catch (err) {
  748. this.log(err);
  749. ctx.body = { err: 1, msg: err.toString(), data: null };
  750. }
  751. }
  752. /**
  753. * 上报和重新上报
  754. * @param ctx
  755. * @return {Promise<void>}
  756. */
  757. async startAudit(ctx) {
  758. try {
  759. // 检查权限等
  760. if (!ctx.change) {
  761. throw '数据错误';
  762. }
  763. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  764. throw '您无权上报该变更令数据';
  765. }
  766. if (!(ctx.change.status === audit.flow.status.uncheck || ctx.change.status === audit.flow.status.back)) {
  767. throw '该变更令当前无法上报';
  768. }
  769. await ctx.service.changeAudit.start(ctx.change.cid, ctx.change.times);
  770. ctx.redirect(ctx.request.header.referer);
  771. } catch (err) {
  772. this.log(err);
  773. ctx.session.postError = err.toString();
  774. ctx.redirect(ctx.request.header.referer);
  775. }
  776. }
  777. // 审批相关
  778. /**
  779. * 添加审批人
  780. * @param ctx
  781. * @return {Promise<void>}
  782. */
  783. async addAudit(ctx) {
  784. try {
  785. const data = JSON.parse(ctx.request.body.data);
  786. const id = this.app._.toInteger(data.auditorId);
  787. if (isNaN(id) || id <= 0) {
  788. throw '参数错误';
  789. }
  790. // 检查权限等
  791. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  792. throw '您无权添加审核人';
  793. }
  794. if (ctx.change.status === audit.flow.status.checking || ctx.change.status === audit.flow.status.checked) {
  795. throw '当前不允许添加审核人';
  796. }
  797. const auditorList = await ctx.service.changeAudit.getAuditors(ctx.change.cid, ctx.change.times);
  798. // 检查审核人是否已存在
  799. const exist = this.app._.find(auditorList, { uid: id });
  800. if (exist) {
  801. throw '该审核人已存在,请勿重复添加';
  802. }
  803. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdzs });
  804. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs ? 1 : 0;
  805. const result = await ctx.service.changeAudit.addAuditor(ctx.change.cid, id, ctx.change.times, is_gdzs);
  806. if (!result) {
  807. throw '添加审核人失败';
  808. }
  809. // const auditors = await ctx.service.changeAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  810. const auditors = null;
  811. ctx.body = { err: 0, msg: '', data: auditors };
  812. } catch (err) {
  813. this.log(err);
  814. ctx.body = { err: 1, msg: err.toString(), data: null };
  815. }
  816. }
  817. /**
  818. * 移除审批人
  819. * @param ctx
  820. * @return {Promise<void>}
  821. */
  822. async deleteAudit(ctx) {
  823. try {
  824. const data = JSON.parse(ctx.request.body.data);
  825. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  826. if (isNaN(id) || id <= 0) {
  827. throw '参数错误';
  828. }
  829. const result = await ctx.service.changeAudit.deleteAuditor(ctx.change.cid, id, ctx.change.times);
  830. if (!result) {
  831. throw '移除审核人失败';
  832. }
  833. const auditors = null;
  834. ctx.body = { err: 0, msg: '', data: auditors };
  835. } catch (err) {
  836. ctx.body = { err: 1, msg: err.toString(), data: null };
  837. }
  838. }
  839. async defaultBills(ctx) {
  840. try {
  841. const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  842. const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  843. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  844. ctx.body = { err: 0, msg: '', data: { bills: ledgerData, pos: posData, dealBills } };
  845. } catch (err) {
  846. this.log(err);
  847. ctx.body = { err: 1, msg: err.toString(), data: [] };
  848. }
  849. }
  850. /**
  851. * 变更令上报和保存
  852. * @param {Object} ctx - egg全局变量
  853. * @return {void}
  854. */
  855. async save(ctx) {
  856. // 变更令信息
  857. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  858. try {
  859. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  860. if (!result) {
  861. throw '上报失败';
  862. }
  863. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  864. ctx.body = { err: 0, msg: '保存成功' };
  865. } else {
  866. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  867. }
  868. } catch (err) {
  869. this.log(err);
  870. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  871. ctx.body = { err: 1, msg: err.toString() };
  872. } else {
  873. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  874. }
  875. }
  876. }
  877. /**
  878. * 变更令审批
  879. * @param {Object} ctx - egg全局变量
  880. * @return {void}
  881. */
  882. async approval(ctx) {
  883. try {
  884. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.change_id });
  885. if (!changeData) {
  886. throw '变更令数据错误';
  887. }
  888. const status = parseInt(ctx.request.body.status);
  889. let result = false;
  890. const pid = this.ctx.session.sessionProject.id;
  891. switch (status) {
  892. case 3:// 审批通过
  893. result = await ctx.service.change.approvalSuccess(pid, ctx.request.body, changeData);
  894. break;
  895. case 4:// 审批终止
  896. result = await ctx.service.change.approvalStop(ctx.request.body);
  897. break;
  898. case 5:// 审批退回到原报人
  899. result = await ctx.service.change.approvalBack(pid, ctx.request.body, changeData);
  900. break;
  901. case 6:// 审批退回到上一个审批人
  902. result = await ctx.service.change.approvalBackNew(pid, ctx.request.body, changeData);
  903. break;
  904. default:break;
  905. }
  906. if (!result) {
  907. throw '审批失败';
  908. }
  909. ctx.redirect(ctx.request.header.referer);
  910. } catch (err) {
  911. console.log(err);
  912. ctx.redirect(ctx.request.header.referer);
  913. }
  914. }
  915. /**
  916. * 变更公司管理
  917. * @param {Object} ctx - egg全局变量
  918. * @return {void}
  919. */
  920. async updateCompany(ctx) {
  921. const responseData = {
  922. err: 0,
  923. msg: '',
  924. data: '',
  925. };
  926. try {
  927. const data = JSON.parse(ctx.request.body.data);
  928. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  929. throw '参数有误';
  930. }
  931. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  932. responseData.data = { add: addCompany, select: selectCompany };
  933. } catch (err) {
  934. responseData.err = 1;
  935. responseData.msg = err;
  936. }
  937. ctx.body = responseData;
  938. }
  939. /**
  940. * 上传附件
  941. * @param {Object} ctx - egg全局变量
  942. * @return {void}
  943. */
  944. async uploadFile(ctx) {
  945. const responseData = {
  946. err: 0,
  947. msg: '',
  948. data: [],
  949. };
  950. let stream;
  951. try {
  952. const parts = ctx.multipart({ autoFields: true });
  953. const files = [];
  954. let index = 0;
  955. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  956. const extra_upload = change.status === audit.flow.status.checked;
  957. while ((stream = await parts()) !== undefined) {
  958. // 判断用户是否选择上传文件
  959. if (!stream.filename) {
  960. throw '请选择上传的文件!';
  961. }
  962. // const create_time = Date.parse(new Date()) / 1000;
  963. // const fileInfo = path.parse(stream.filename);
  964. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  965. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  966. // // 判断文件夹是否存在,不存在则直接创建文件夹
  967. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  968. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  969. // }
  970. // // 保存文件
  971. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  972. const fileInfo = path.parse(stream.filename);
  973. const create_time = Date.parse(new Date()) / 1000;
  974. const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  975. await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  976. await sendToWormhole(stream);
  977. // 保存数据到att表
  978. const fileData = {
  979. in_time: create_time,
  980. filename: fileInfo.name,
  981. fileext: fileInfo.ext,
  982. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  983. filepath,
  984. extra_upload,
  985. };
  986. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  987. if (!result) {
  988. throw '导入数据库保存失败';
  989. }
  990. fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  991. fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  992. fileData.id = result.insertId;
  993. delete fileData.filepath;
  994. files.push(fileData);
  995. ++index;
  996. }
  997. responseData.data = files;
  998. } catch (err) {
  999. this.log(err);
  1000. // 失败需要消耗掉stream 以防卡死
  1001. if (stream) {
  1002. await sendToWormhole(stream);
  1003. }
  1004. this.setMessage(err.toString(), this.messageType.ERROR);
  1005. }
  1006. ctx.body = responseData;
  1007. }
  1008. /**
  1009. * 下载附件
  1010. * @param {Object} ctx - egg全局变量
  1011. * @return {void}
  1012. */
  1013. async downloadFile(ctx) {
  1014. const id = ctx.params.id;
  1015. if (id) {
  1016. try {
  1017. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1018. if (fileInfo !== undefined && fileInfo !== '') {
  1019. const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  1020. // 解决中文无法下载问题
  1021. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1022. let disposition = '';
  1023. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1024. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  1025. } else if (userAgent.indexOf('firefox') >= 0) {
  1026. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  1027. } else {
  1028. /* safari等其他非主流浏览器只能自求多福了 */
  1029. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  1030. }
  1031. ctx.response.set({
  1032. 'Content-Type': 'application/octet-stream',
  1033. 'Content-Disposition': disposition,
  1034. 'Content-Length': fileInfo.filesize,
  1035. });
  1036. ctx.body = await fs.createReadStream(fileName);
  1037. } else {
  1038. throw '不存在该文件';
  1039. }
  1040. } catch (err) {
  1041. this.log(err);
  1042. this.setMessage(err.toString(), this.messageType.ERROR);
  1043. }
  1044. }
  1045. }
  1046. /**
  1047. * 批量下载 - 压缩成zip文件返回
  1048. * @param {Oject} ctx - 全局上下文
  1049. */
  1050. async downloadZip(ctx) {
  1051. try {
  1052. const fileIds = JSON.parse(ctx.request.query.fileIds);
  1053. // const { fileIds } = JSON.parse(ctx.request.body.data);
  1054. // console.log('fileIds', fileIds);
  1055. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  1056. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  1057. const time = Date.now();
  1058. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  1059. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  1060. // 解决中文无法下载问题
  1061. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1062. let disposition = '';
  1063. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1064. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  1065. } else if (userAgent.indexOf('firefox') >= 0) {
  1066. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  1067. } else {
  1068. /* safari等其他非主流浏览器只能自求多福了 */
  1069. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  1070. }
  1071. ctx.response.set({
  1072. 'Content-Type': 'application/octet-stream',
  1073. 'Content-Disposition': disposition,
  1074. 'Content-Length': size,
  1075. });
  1076. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  1077. ctx.body = readStream;
  1078. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  1079. readStream.on('close', () => {
  1080. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1081. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1082. }
  1083. });
  1084. } catch (error) {
  1085. this.log(error);
  1086. }
  1087. }
  1088. /**
  1089. * 删除附件
  1090. * @param {Object} ctx - egg全局变量
  1091. * @return {void}
  1092. */
  1093. async deleteFile(ctx) {
  1094. const responseData = {
  1095. err: 0,
  1096. msg: '',
  1097. data: '',
  1098. };
  1099. try {
  1100. const data = JSON.parse(ctx.request.body.data);
  1101. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1102. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  1103. if (!fileInfo || !Object.keys(fileInfo).length) {
  1104. throw '该文件不存在';
  1105. }
  1106. if (!fileInfo.extra_upload && change.status === audit.flow.status.checked) {
  1107. throw '无权限删除';
  1108. }
  1109. if (fileInfo !== undefined && fileInfo !== '') {
  1110. // 先删除文件
  1111. await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  1112. // 再删除数据库
  1113. await ctx.service.changeAtt.deleteById(data.id);
  1114. responseData.data = '';
  1115. } else {
  1116. throw '不存在该文件';
  1117. }
  1118. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1119. // throw '参数有误';
  1120. // }
  1121. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1122. // responseData.data = { add: addCompany, select: selectCompany };
  1123. } catch (err) {
  1124. responseData.err = 1;
  1125. responseData.msg = err;
  1126. }
  1127. ctx.body = responseData;
  1128. }
  1129. /**
  1130. * 查看附件
  1131. * @param {Object} ctx - egg全局变量
  1132. * @return {void}
  1133. */
  1134. async checkFile(ctx) {
  1135. const responseData = { err: 0, msg: '' };
  1136. const id = parseInt(ctx.params.id);
  1137. if (id) {
  1138. try {
  1139. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1140. if (fileInfo && Object.keys(fileInfo).length) {
  1141. let filepath = fileInfo.filepath;
  1142. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  1143. filepath = `/change/download/file/${fileInfo.id}`;
  1144. } else {
  1145. filepath = filepath.replace(/^app|\/app/, '');
  1146. }
  1147. fileInfo.filepath && (responseData.data = { filepath });
  1148. }
  1149. } catch (error) {
  1150. this.log(error);
  1151. this.setMessage(error.toString(), this.messageType.ERROR);
  1152. responseData.err = 1;
  1153. responseData.msg = error.toString();
  1154. }
  1155. }
  1156. ctx.body = responseData;
  1157. }
  1158. /**
  1159. * 删除变更令
  1160. * @param {Object} ctx - egg全局变量
  1161. * @return {void}
  1162. */
  1163. async delete(ctx) {
  1164. try {
  1165. const result = await ctx.service.change.delete(ctx.request.body.cid);
  1166. if (!result) {
  1167. throw '删除变更令失败';
  1168. }
  1169. ctx.redirect(ctx.request.header.referer);
  1170. } catch (err) {
  1171. console.log(err);
  1172. ctx.redirect(ctx.request.header.referer);
  1173. }
  1174. }
  1175. /**
  1176. * 变更令重新审批
  1177. * @param {Object} ctx - egg全局变量
  1178. * @return {void}
  1179. */
  1180. async checkAgain(ctx) {
  1181. try {
  1182. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1183. if (!changeData) {
  1184. throw '变更令数据错误';
  1185. }
  1186. // 获取终审
  1187. const auditInfo = (await this.ctx.service.changeAudit.getAllDataByCondition({ where: { cid: changeData.cid }, orders: [['usort', 'desc']], limit: 1, offset: 0 }))[0];
  1188. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== auditInfo.uid) {
  1189. throw '您无权进行该操作';
  1190. }
  1191. if (ctx.session.sessionUser.loginStatus === 0) {
  1192. const code = ctx.request.body.code;
  1193. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1194. if (!pa.auth_mobile) {
  1195. throw '未绑定手机号';
  1196. }
  1197. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1198. const cacheCode = await app.redis.get(cacheKey);
  1199. // console.log(cacheCode);
  1200. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1201. throw '验证码不正确!';
  1202. }
  1203. }
  1204. // 获取是否已存在调用变更令
  1205. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, changeData.cid);
  1206. const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  1207. if (stageChangeNum !== 0) {
  1208. throw '该变更令已被调用,无法重新审批';
  1209. }
  1210. // 重新审批
  1211. const result = await ctx.service.change.checkAgain(changeData.cid);
  1212. if (!result) {
  1213. throw '重新审批失败';
  1214. }
  1215. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1216. ctx.body = {
  1217. err: 0,
  1218. url: ctx.request.header.referer,
  1219. msg: '',
  1220. };
  1221. } catch (err) {
  1222. console.log(err);
  1223. // ctx.redirect(ctx.request.header.referer);
  1224. ctx.body = {
  1225. err: 1,
  1226. // url: ctx.request.header.referer,
  1227. msg: err,
  1228. };
  1229. }
  1230. }
  1231. /**
  1232. * 获取变更清单
  1233. * @param ctx
  1234. * @return {Promise<void>}
  1235. */
  1236. async bills(ctx) {
  1237. try {
  1238. const data = JSON.parse(ctx.request.body.data);
  1239. const responseData = { err: 0, msg: '', data: [] };
  1240. switch (data.type) {
  1241. case 'gather':
  1242. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  1243. break;
  1244. default:
  1245. throw '查询的数据不存在';
  1246. }
  1247. ctx.body = responseData;
  1248. } catch (err) {
  1249. this.log(err);
  1250. this.ajaxErrorBody(err, '获取变更清单失败');
  1251. }
  1252. }
  1253. /**
  1254. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  1255. * @param ctx
  1256. * @return {Promise<void>}
  1257. */
  1258. async checkCodeRepeat(ctx) {
  1259. const responseData = {
  1260. err: 0,
  1261. msg: '',
  1262. data: '',
  1263. };
  1264. try {
  1265. const tenderId = ctx.params.id;
  1266. const cid = ctx.params.cid;
  1267. const data = JSON.parse(ctx.request.body.data);
  1268. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  1269. if (result) {
  1270. throw '该变更令号(批复编号)已使用';
  1271. }
  1272. } catch (err) {
  1273. responseData.err = 1;
  1274. responseData.msg = err;
  1275. }
  1276. ctx.body = responseData;
  1277. }
  1278. /**
  1279. * 拷贝其他变更令
  1280. * @param {object} ctx - 全局上下文
  1281. */
  1282. async copyChange(ctx) {
  1283. const responseData = {
  1284. err: 0,
  1285. msg: '',
  1286. data: '',
  1287. };
  1288. try {
  1289. const cid = ctx.params.cid;
  1290. const copy_cid = JSON.parse(ctx.request.body.data);
  1291. const result = await ctx.service.change.handleCopyChange(cid, copy_cid);
  1292. if (!result) {
  1293. responseData.err = 1;
  1294. responseData.msg = '拷贝失败!';
  1295. }
  1296. } catch (error) {
  1297. responseData.err = 1;
  1298. responseData.msg = error;
  1299. }
  1300. ctx.body = responseData;
  1301. }
  1302. }
  1303. return ChangeController;
  1304. };