change_controller.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2018/8/14
  7. * @version
  8. */
  9. const moment = require('moment');
  10. const fs = require('fs');
  11. const path = require('path');
  12. const audit = require('../const/audit');
  13. const codeRuleConst = require('../const/code_rule');
  14. const changeConst = require('../const/change');
  15. const accountGroup = require('../const/account_group').group;
  16. const shenpiConst = require('../const/shenpi');
  17. // const tenderMenu = require('../../config/menu').tenderMenu;
  18. module.exports = app => {
  19. class ChangeController extends app.BaseController {
  20. /**
  21. * 构造函数
  22. *
  23. * @param {Object} ctx - egg全局变量
  24. * @return {void}
  25. */
  26. constructor(ctx) {
  27. super(ctx);
  28. ctx.showProject = true;
  29. ctx.showTender = true;
  30. ctx.showTitle = true;
  31. }
  32. async _filterChanges(ctx, status = 0) {
  33. const tenderId = ctx.params.id;
  34. ctx.session.sessionUser.tenderId = tenderId;
  35. const tender = await this.service.tender.getDataById(tenderId);
  36. // const tenderList = await this.service.tender.getList();
  37. const page = ctx.page;
  38. const changes = await ctx.service.change.getListByStatus(tender.id, status);
  39. const total = await ctx.service.change.getCountByStatus(tender.id, status);
  40. if (changes !== null) {
  41. let i = 0;
  42. for (const c of changes) {
  43. const status = c.status === audit.flow.status.uncheck ? 0 : 1;
  44. // 根据审批人对当前变更令的状态取不同的展示方式。
  45. let changeAudit = '';
  46. let auditStatus = 0;
  47. switch (c.status) {
  48. case 1:
  49. auditStatus = 1;
  50. break;
  51. case 2:
  52. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  53. auditStatus = changeAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  54. break;
  55. case 3:
  56. case 4:
  57. auditStatus = 0;
  58. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  59. break;
  60. case 5:
  61. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times - 1, status);
  62. auditStatus = c.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  63. break;
  64. case 6:
  65. changeAudit = await ctx.service.changeAudit.getLastBackUser(c.cid, c.times);
  66. const checkingAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  67. auditStatus = checkingAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  68. break;
  69. default:
  70. break;
  71. }
  72. changes[i].changeAudit = changeAudit;
  73. changes[i].auditStatus = auditStatus;
  74. i++;
  75. }
  76. }
  77. // 分页相关
  78. const pageInfo = {
  79. page,
  80. total: Math.ceil(total / app.config.pageSize),
  81. queryData: JSON.stringify(ctx.urlInfo.query),
  82. };
  83. const filter = JSON.parse(JSON.stringify(audit.filter));
  84. filter.count = [];
  85. 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);
  86. 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);
  87. 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);
  88. 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);
  89. 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);
  90. const codeRule = tender.c_rule ? JSON.parse(tender.c_rule) : [];
  91. for (const rule of codeRule) {
  92. switch (rule.rule_type) {
  93. case codeRuleConst.measure.ruleType.dealCode:
  94. rule.preview = ctx.tender.info.deal_info.dealCode;
  95. break;
  96. case codeRuleConst.measure.ruleType.tenderName:
  97. rule.preview = tender.name;
  98. break;
  99. case codeRuleConst.measure.ruleType.inDate:
  100. rule.preview = moment().format('YYYY');
  101. break;
  102. case codeRuleConst.measure.ruleType.text:
  103. rule.preview = rule.text;
  104. break;
  105. case codeRuleConst.measure.ruleType.addNo:
  106. const s = '0000000000';
  107. rule.preview = s.substr(s.length - rule.format);
  108. break;
  109. default: break;
  110. }
  111. }
  112. const renderData = {
  113. uid: ctx.session.sessionUser.accountId,
  114. moment,
  115. tender,
  116. // tenderList,
  117. pageInfo,
  118. changes,
  119. filter,
  120. status,
  121. codeRule,
  122. dealCode: ctx.tender.info.deal_info.dealCode,
  123. auditConst: audit.flow,
  124. changeConst,
  125. ruleType: codeRuleConst.ruleType.change,
  126. ruleConst: codeRuleConst.measure,
  127. tenderMenu: this.menu.tenderMenu,
  128. preUrl: '/tender/' + tenderId,
  129. tpUnit: ctx.tender.info.decimal.tp,
  130. };
  131. await this.layout('change/index.ejs', renderData, 'change/modal.ejs');
  132. }
  133. /**
  134. * 变更管理 页面 (Get)
  135. *
  136. * @param {Object} ctx - egg全局变量
  137. * @return {void}
  138. */
  139. async index(ctx) {
  140. try {
  141. await this._filterChanges(ctx);
  142. } catch (err) {
  143. this.log(err);
  144. ctx.redirect('/dashboard');
  145. }
  146. }
  147. /**
  148. *
  149. * @param {Object} ctx - egg全局变量
  150. * @return {void}
  151. */
  152. async newCode(ctx) {
  153. const responseData = {
  154. err: 0,
  155. msg: '',
  156. data: '',
  157. };
  158. try {
  159. const tenderId = ctx.params.id;
  160. if (!tenderId) {
  161. throw '当前未打开标段';
  162. }
  163. const tenderData = await ctx.service.tender.getDataById(tenderId);
  164. const cCodeRule = tenderData.c_rule !== null ? JSON.parse(tenderData.c_rule) : [];
  165. const code = [];
  166. for (const rule of cCodeRule) {
  167. switch (rule.rule_type) {
  168. case codeRuleConst.measure.ruleType.dealCode:
  169. code.push(ctx.tender.info.deal_info.dealCode);
  170. break;
  171. case codeRuleConst.measure.ruleType.tenderName:
  172. code.push(tenderData.name);
  173. break;
  174. case codeRuleConst.measure.ruleType.text:
  175. code.push(rule.text);
  176. break;
  177. case codeRuleConst.measure.ruleType.inDate:
  178. code.push(moment().format('YYYY'));
  179. break;
  180. case codeRuleConst.measure.ruleType.addNo:
  181. let s = '0000000000';
  182. const count = rule.start + await ctx.service.change.count({ tid: tenderId });
  183. s = s + count;
  184. code.push(s.substr(s.length - rule.format));
  185. break;
  186. default: break;
  187. }
  188. }
  189. responseData.data = code.join(tenderData.c_connector !== null && tenderData.c_connector !== 3 ? codeRuleConst.measure.connectorString[tenderData.c_connector] : '');
  190. } catch (err) {
  191. responseData.err = 1;
  192. responseData.msg = err;
  193. }
  194. ctx.body = responseData;
  195. }
  196. /**
  197. * 新增变更 (Post)
  198. *
  199. * @param {Object} ctx - egg全局变量
  200. * @return {void}
  201. */
  202. async add(ctx) {
  203. try {
  204. const tenderId = ctx.params.id;
  205. if (!tenderId) {
  206. throw '当前未打开标段';
  207. }
  208. const data = JSON.parse(ctx.request.body.data);
  209. if (!data.code || data.code === '' || !data.name || data.name === '') {
  210. throw '变更令号不能为空';
  211. }
  212. const change = await ctx.service.change.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  213. ctx.body = { err: 0, msg: '', data: change };
  214. } catch (err) {
  215. this.log(err);
  216. ctx.body = { err: 1, msg: err.toString() };
  217. }
  218. }
  219. /**
  220. * 变更管理 状态筛选 页面 (Get)
  221. * @param {Object} ctx - egg全局变量
  222. * @return {void}
  223. */
  224. async status(ctx) {
  225. try {
  226. const status = parseInt(ctx.params.status);
  227. await this._filterChanges(ctx, status);
  228. } catch (err) {
  229. this.logger.error(err);
  230. ctx.redirect('/tender/' + ctx.params.id + '/change');
  231. }
  232. }
  233. /**
  234. * 变更信息 页面 (Get)
  235. *
  236. * @param {Object} ctx - egg全局变量
  237. * @return {void}
  238. */
  239. async info(ctx) {
  240. try {
  241. const whiteList = this.ctx.app.config.multipart.whitelist;
  242. const tenderid = ctx.params.id !== undefined ? ctx.params.id : ctx.session.sessionUser.tenderId;
  243. ctx.session.sessionUser.tenderId = tenderid;
  244. const tender = await ctx.service.tender.getDataById(tenderid);
  245. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  246. // 后台判断当前人查看info状态
  247. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  248. // 获取附件列表
  249. const attList = await ctx.service.changeAtt.getChangeAttachment(ctx.params.cid);
  250. // 获取其他变更令数据
  251. const othersChange = await ctx.service.change.getOthersChange(ctx.params.id, ctx.params.cid);
  252. // 根据auditStatus获取审批人列表
  253. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  254. // 获取已选清单
  255. let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  256. // 获取用户人验证手机号
  257. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  258. const auth_mobile = pa.auth_mobile;
  259. const renderData = {
  260. uid: ctx.session.sessionUser.accountId,
  261. tender,
  262. change,
  263. othersChange,
  264. changeConst,
  265. auditStatus,
  266. auditConst: audit.flow,
  267. ledgerConsts: audit.ledger.status,
  268. attList,
  269. whiteList,
  270. auditList,
  271. changeList,
  272. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  273. upUnit: ctx.tender.info.decimal.up,
  274. authMobile: auth_mobile,
  275. shenpiConst,
  276. };
  277. // 根据auditStatus状态获取的不同的数据
  278. if (auditStatus === 1 || auditStatus === 2) {
  279. renderData.changeUnits = changeConst.units;
  280. renderData.precision = ctx.tender.info.precision;
  281. // renderData.accountGroup = accountGroup;
  282. // 获取所有项目参与者
  283. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  284. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  285. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  286. });
  287. renderData.accountList = accountList;
  288. renderData.accountGroup = accountGroup.map((item, idx) => {
  289. const groupList = accountList.filter(item => item.account_group === idx);
  290. return { groupName: item, groupList };
  291. });
  292. // 重新上报获取审批流程
  293. if (auditStatus === 2) {
  294. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  295. // 展示页右侧审批流程列表
  296. const auditList3 = [];
  297. for (let time = 1; time <= change.times - 1; time++) {
  298. const auditTimeList = [];
  299. let max_sort = 1;
  300. for (const al of auditList2) {
  301. if (al.times === time) {
  302. auditTimeList.push(al);
  303. if (al.usite > max_sort) {
  304. max_sort = al.usite;
  305. }
  306. }
  307. }
  308. for (const i in auditTimeList) {
  309. auditTimeList[i].max_sort = max_sort;
  310. }
  311. auditList3.push(auditTimeList);
  312. }
  313. renderData.auditList3 = auditList3;
  314. }
  315. // 根据清单获取提交数据和计算总金额
  316. const changeListData = [];
  317. const changeWhiteListData = [];
  318. let ototalCost = 0;
  319. let ctotalCost = 0;
  320. for (const cl of changeList) {
  321. const cLArray = [
  322. cl.code,
  323. cl.name,
  324. cl.bwmx,
  325. cl.unit,
  326. cl.unit_price,
  327. cl.oamount,
  328. cl.camount,
  329. cl.detail,
  330. cl.lid,
  331. cl.xmj_code,
  332. cl.xmj_jldy,
  333. cl.gcl_id,
  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. /**
  492. * 变更信息 新版本页面 (Get)
  493. *
  494. * @param {Object} ctx - egg全局变量
  495. * @return {void}
  496. */
  497. async information(ctx) {
  498. try {
  499. const whiteList = this.ctx.app.config.multipart.whitelist;
  500. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  501. const change = ctx.change;
  502. // 后台判断当前人查看info状态
  503. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  504. // 获取附件列表
  505. const attList = await ctx.service.changeAtt.getChangeAttachment(change.cid, 'desc');
  506. // 获取其他变更令数据
  507. const othersChange = await ctx.service.change.getOthersChange(ctx.tender.id, change.cid);
  508. // 根据auditStatus获取审批人列表
  509. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  510. // 获取用户人验证手机号
  511. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  512. const auth_mobile = pa.auth_mobile;
  513. const renderData = {
  514. tender,
  515. change,
  516. othersChange,
  517. changeConst,
  518. auditStatus,
  519. auditConst: audit.flow,
  520. ledgerConsts: audit.ledger.status,
  521. attList,
  522. whiteList,
  523. auditList,
  524. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  525. upUnit: ctx.tender.info.decimal.up,
  526. authMobile: auth_mobile,
  527. shenpiConst,
  528. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.information),
  529. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  530. precision: ctx.tender.info.precision,
  531. };
  532. // 根据auditStatus状态获取的不同的数据
  533. if (auditStatus === 1 || auditStatus === 2) {
  534. renderData.changeUnits = changeConst.units;
  535. // renderData.accountGroup = accountGroup;
  536. // 获取所有项目参与者
  537. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  538. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  539. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  540. });
  541. renderData.accountList = accountList;
  542. renderData.accountGroup = accountGroup.map((item, idx) => {
  543. const groupList = accountList.filter(item => item.account_group === idx);
  544. return { groupName: item, groupList };
  545. });
  546. // 重新上报获取审批流程
  547. if (auditStatus === 2) {
  548. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  549. // 展示页右侧审批流程列表
  550. const auditList3 = [];
  551. for (let time = 1; time <= change.times - 1; time++) {
  552. const auditTimeList = [];
  553. let max_sort = 1;
  554. for (const al of auditList2) {
  555. if (al.times === time) {
  556. auditTimeList.push(al);
  557. if (al.usite > max_sort) {
  558. max_sort = al.usite;
  559. }
  560. }
  561. }
  562. for (const i in auditTimeList) {
  563. auditTimeList[i].max_sort = max_sort;
  564. }
  565. auditList3.push(auditTimeList);
  566. }
  567. renderData.auditList3 = auditList3;
  568. }
  569. // 获取公司列表
  570. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  571. renderData.companyList = companyList;
  572. // 获取已选清单
  573. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  574. renderData.changeList = changeList;
  575. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7) {
  576. // 展示页左侧审批流程列表和清单审批列表数据
  577. const times = change.status === audit.flow.status.back ?
  578. change.times - 1 : change.times;
  579. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  580. // 展示页右侧审批流程列表
  581. const auditList3 = [];
  582. for (let time = 1; time <= times; time++) {
  583. const auditTimeList = [];
  584. let max_sort = 1;
  585. for (const al of auditList) {
  586. if (al.times === time) {
  587. auditTimeList.push(al);
  588. if (al.usite > max_sort) {
  589. max_sort = al.usite;
  590. }
  591. }
  592. }
  593. for (const i in auditTimeList) {
  594. auditTimeList[i].max_sort = max_sort;
  595. }
  596. auditList3.push(auditTimeList);
  597. }
  598. renderData.auditList3 = auditList3;
  599. // 获取已选清单
  600. // let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  601. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  602. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  603. for (const cl of changeList) {
  604. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  605. // 清单表页赋值
  606. for (const [index, au] of auditList2.entries()) {
  607. if (au.usite !== 0) {
  608. cl['audit_amount_' + au.uid] = audit_amount[index - 1] ? audit_amount[index - 1] : null;
  609. }
  610. }
  611. }
  612. renderData.changeList = changeList;
  613. renderData.auditList2 = auditList2;
  614. } else if (auditStatus === 6) {
  615. // 展示页左侧审批流程列表和清单审批列表数据
  616. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  617. renderData.auditList2 = auditList2;
  618. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  619. for (const i in auditList3) {
  620. auditList3[i].max_sort = auditList2.length - 1;
  621. }
  622. renderData.auditList3 = auditList3;
  623. // 展示页右侧审批流程列表
  624. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  625. const auditList4 = [];
  626. for (let time = 1; time <= change.times; time++) {
  627. const auditTimeList = [];
  628. let max_sort = 1;
  629. for (const al of auditList5) {
  630. if (al.times === time) {
  631. auditTimeList.push(al);
  632. if (al.usite > max_sort) {
  633. max_sort = al.usite;
  634. }
  635. }
  636. }
  637. for (const i in auditTimeList) {
  638. auditTimeList[i].max_sort = max_sort;
  639. }
  640. if (auditTimeList.length > 0) {
  641. auditList4.push(auditTimeList);
  642. }
  643. }
  644. renderData.auditList4 = auditList4;
  645. // 获取已选清单
  646. // let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  647. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  648. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  649. for (const cl of changeList) {
  650. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  651. // 清单表页赋值
  652. for (const [index, au] of auditList2.entries()) {
  653. if (au.usite !== 0) {
  654. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  655. }
  656. }
  657. }
  658. renderData.changeList = changeList;
  659. }
  660. renderData.auditList = auditList;
  661. // 获取是否已存在调用变更令
  662. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  663. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  664. await this.layout('change/information.ejs', renderData, 'change/information_modal.ejs');
  665. } catch (err) {
  666. this.log(err);
  667. ctx.redirect('/tender/' + ctx.params.id + '/change');
  668. }
  669. }
  670. /**
  671. * 变更清单 - 操作 (Ajax)
  672. * @param ctx
  673. * @return {Promise<void>}
  674. */
  675. async saveListsData(ctx) {
  676. try {
  677. const data = JSON.parse(ctx.request.body.data);
  678. const responseData = {
  679. err: 0,
  680. msg: '',
  681. data: {},
  682. };
  683. switch (data.type) {
  684. case 'add':
  685. responseData.data = await ctx.service.changeAuditList.add(data.postData);
  686. break;
  687. case 'del':
  688. await ctx.service.changeAuditList.del(data.id);
  689. break;
  690. case 'update':
  691. await ctx.service.changeAuditList.save(data.updateData);
  692. break;
  693. case 'paste':
  694. await ctx.service.changeAuditList.saveDatas(data.updateData);
  695. // 取所有工料表
  696. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  697. break;
  698. case 'ledger_list':
  699. await ctx.service.changeAuditList.saveLedgerListDatas(data.updateData);
  700. // 取所有工料表
  701. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  702. break;
  703. case 'remove_list':
  704. await ctx.service.changeAuditList.removeLedgerListDatas(data.updateData);
  705. // 取所有工料表
  706. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  707. break;
  708. case 'info':
  709. await ctx.service.change.saveInfo(data.updateData);
  710. // 取所有工料表
  711. responseData.data = '保存成功';
  712. break;
  713. case 'paste_amount_rows':
  714. await ctx.service.changeAuditList.saveDatas(data.updateData);
  715. let changeList = await ctx.service.changeAuditList.getList(ctx.change.cid);
  716. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times);
  717. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  718. for (const cl of changeList) {
  719. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  720. // 清单表页赋值
  721. for (const [index, au] of auditList2.entries()) {
  722. if (au.usite !== 0) {
  723. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  724. }
  725. }
  726. }
  727. // 取所有工料表
  728. responseData.data = changeList;
  729. break;
  730. default: throw '参数有误';
  731. }
  732. ctx.body = responseData;
  733. } catch (err) {
  734. this.log(err);
  735. ctx.body = { err: 1, msg: err.toString(), data: null };
  736. }
  737. }
  738. /**
  739. * 上报和重新上报
  740. * @param ctx
  741. * @return {Promise<void>}
  742. */
  743. async startAudit(ctx) {
  744. try {
  745. // 检查权限等
  746. if (!ctx.change) {
  747. throw '数据错误';
  748. }
  749. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  750. throw '您无权上报该变更令数据';
  751. }
  752. if (!(ctx.change.status === audit.flow.status.uncheck || ctx.change.status === audit.flow.status.back)) {
  753. throw '该变更令当前无法上报';
  754. }
  755. await ctx.service.changeAudit.start(ctx.change.cid, ctx.change.times);
  756. ctx.redirect(ctx.request.header.referer);
  757. } catch (err) {
  758. this.log(err);
  759. ctx.session.postError = err.toString();
  760. ctx.redirect(ctx.request.header.referer);
  761. }
  762. }
  763. // 审批相关
  764. /**
  765. * 添加审批人
  766. * @param ctx
  767. * @return {Promise<void>}
  768. */
  769. async addAudit(ctx) {
  770. try {
  771. const data = JSON.parse(ctx.request.body.data);
  772. const id = this.app._.toInteger(data.auditorId);
  773. if (isNaN(id) || id <= 0) {
  774. throw '参数错误';
  775. }
  776. // 检查权限等
  777. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  778. throw '您无权添加审核人';
  779. }
  780. if (ctx.change.status === audit.flow.status.checking || ctx.change.status === audit.flow.status.checked) {
  781. throw '当前不允许添加审核人';
  782. }
  783. const auditorList = await ctx.service.changeAudit.getAuditors(ctx.change.cid, ctx.change.times);
  784. // 检查审核人是否已存在
  785. const exist = this.app._.find(auditorList, { uid: id });
  786. if (exist) {
  787. throw '该审核人已存在,请勿重复添加';
  788. }
  789. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdzs });
  790. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs ? 1 : 0;
  791. const result = await ctx.service.changeAudit.addAuditor(ctx.change.cid, id, ctx.change.times, is_gdzs);
  792. if (!result) {
  793. throw '添加审核人失败';
  794. }
  795. // const auditors = await ctx.service.changeAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  796. const auditors = null;
  797. ctx.body = { err: 0, msg: '', data: auditors };
  798. } catch (err) {
  799. this.log(err);
  800. ctx.body = { err: 1, msg: err.toString(), data: null };
  801. }
  802. }
  803. /**
  804. * 移除审批人
  805. * @param ctx
  806. * @return {Promise<void>}
  807. */
  808. async deleteAudit(ctx) {
  809. try {
  810. const data = JSON.parse(ctx.request.body.data);
  811. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  812. if (isNaN(id) || id <= 0) {
  813. throw '参数错误';
  814. }
  815. const result = await ctx.service.changeAudit.deleteAuditor(ctx.change.cid, id, ctx.change.times);
  816. if (!result) {
  817. throw '移除审核人失败';
  818. }
  819. const auditors = null;
  820. ctx.body = { err: 0, msg: '', data: auditors };
  821. } catch (err) {
  822. ctx.body = { err: 1, msg: err.toString(), data: null };
  823. }
  824. }
  825. async defaultBills(ctx) {
  826. try {
  827. const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  828. const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  829. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  830. ctx.body = { err: 0, msg: '', data: { bills: ledgerData, pos: posData, dealBills } };
  831. } catch (err) {
  832. this.log(err);
  833. ctx.body = { err: 1, msg: err.toString(), data: [] };
  834. }
  835. }
  836. /**
  837. * 变更令上报和保存
  838. * @param {Object} ctx - egg全局变量
  839. * @return {void}
  840. */
  841. async save(ctx) {
  842. // 变更令信息
  843. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  844. try {
  845. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  846. if (!result) {
  847. throw '上报失败';
  848. }
  849. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  850. ctx.body = { err: 0, msg: '保存成功' };
  851. } else {
  852. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  853. }
  854. } catch (err) {
  855. this.log(err);
  856. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  857. ctx.body = { err: 1, msg: err.toString() };
  858. } else {
  859. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  860. }
  861. }
  862. }
  863. /**
  864. * 变更令审批
  865. * @param {Object} ctx - egg全局变量
  866. * @return {void}
  867. */
  868. async approval(ctx) {
  869. try {
  870. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.change_id });
  871. if (!changeData) {
  872. throw '变更令数据错误';
  873. }
  874. const status = parseInt(ctx.request.body.status);
  875. let result = false;
  876. const pid = this.ctx.session.sessionProject.id;
  877. switch (status) {
  878. case 3:// 审批通过
  879. result = await ctx.service.change.approvalSuccess(pid, ctx.request.body, changeData);
  880. break;
  881. case 4:// 审批终止
  882. result = await ctx.service.change.approvalStop(ctx.request.body);
  883. break;
  884. case 5:// 审批退回到原报人
  885. result = await ctx.service.change.approvalBack(pid, ctx.request.body, changeData);
  886. break;
  887. case 6:// 审批退回到上一个审批人
  888. result = await ctx.service.change.approvalBackNew(pid, ctx.request.body, changeData);
  889. break;
  890. default:break;
  891. }
  892. if (!result) {
  893. throw '审批失败';
  894. }
  895. ctx.redirect(ctx.request.header.referer);
  896. } catch (err) {
  897. console.log(err);
  898. ctx.redirect(ctx.request.header.referer);
  899. }
  900. }
  901. /**
  902. * 变更公司管理
  903. * @param {Object} ctx - egg全局变量
  904. * @return {void}
  905. */
  906. async updateCompany(ctx) {
  907. const responseData = {
  908. err: 0,
  909. msg: '',
  910. data: '',
  911. };
  912. try {
  913. const data = JSON.parse(ctx.request.body.data);
  914. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  915. throw '参数有误';
  916. }
  917. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  918. responseData.data = { add: addCompany, select: selectCompany };
  919. } catch (err) {
  920. responseData.err = 1;
  921. responseData.msg = err;
  922. }
  923. ctx.body = responseData;
  924. }
  925. /**
  926. * 上传附件
  927. * @param {Object} ctx - egg全局变量
  928. * @return {void}
  929. */
  930. async uploadFile(ctx) {
  931. const responseData = { err: 0, msg: '', data: [], };
  932. try {
  933. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  934. const extra_upload = change.status === audit.flow.status.checked;
  935. const files = [];
  936. let index = 0;
  937. for (const file of ctx.request.files) {
  938. if (!file.filename) throw '请选择上传的文件!';
  939. try {
  940. const fileInfo = path.parse(file.filename);
  941. const create_time = Date.parse(new Date()) / 1000;
  942. const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  943. await this.ctx.helper.recursiveMkdirSync(path.dirname(path.resolve(this.app.baseDir, filepath)));
  944. await fs.copyFileSync(file.filepath, path.resolve(this.app.baseDir, filepath));
  945. const fileData = {
  946. in_time: create_time,
  947. filename: fileInfo.name,
  948. fileext: fileInfo.ext,
  949. filesize: Array.isArray(ctx.request.body.size) ? ctx.request.body.size[index] : ctx.request.body.size,
  950. uid: ctx.session.sessionUser.accountId,
  951. filepath,
  952. extra_upload
  953. };
  954. const result = await ctx.service.changeAtt.save(ctx.request.body, fileData, ctx.session.sessionUser.accountId);
  955. if (!result) {
  956. throw '导入数据库保存失败';
  957. }
  958. fileData.uid = ctx.session.sessionUser.accountId;
  959. fileData.id = result.insertId;
  960. delete fileData.filepath;
  961. files.push(fileData);
  962. ++index;
  963. } finally {
  964. await fs.unlinkSync(file.filepath);
  965. }
  966. }
  967. responseData.data = files;
  968. } catch (err) {
  969. this.log(err);
  970. this.setMessage(err.toString(), this.messageType.ERROR);
  971. }
  972. ctx.body = responseData;
  973. }
  974. /**
  975. * 下载附件
  976. * @param {Object} ctx - egg全局变量
  977. * @return {void}
  978. */
  979. async downloadFile(ctx) {
  980. const id = ctx.params.id;
  981. if (id) {
  982. try {
  983. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  984. if (fileInfo !== undefined && fileInfo !== '') {
  985. const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  986. // 解决中文无法下载问题
  987. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  988. let disposition = '';
  989. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  990. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  991. } else if (userAgent.indexOf('firefox') >= 0) {
  992. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  993. } else {
  994. /* safari等其他非主流浏览器只能自求多福了 */
  995. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  996. }
  997. ctx.response.set({
  998. 'Content-Type': 'application/octet-stream',
  999. 'Content-Disposition': disposition,
  1000. 'Content-Length': fileInfo.filesize,
  1001. });
  1002. ctx.body = await fs.createReadStream(fileName);
  1003. } else {
  1004. throw '不存在该文件';
  1005. }
  1006. } catch (err) {
  1007. this.log(err);
  1008. this.setMessage(err.toString(), this.messageType.ERROR);
  1009. }
  1010. }
  1011. }
  1012. /**
  1013. * 批量下载 - 压缩成zip文件返回
  1014. * @param {Oject} ctx - 全局上下文
  1015. */
  1016. async downloadZip(ctx) {
  1017. try {
  1018. const fileIds = JSON.parse(ctx.request.query.fileIds);
  1019. // const { fileIds } = JSON.parse(ctx.request.body.data);
  1020. // console.log('fileIds', fileIds);
  1021. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  1022. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  1023. const time = Date.now();
  1024. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  1025. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  1026. // 解决中文无法下载问题
  1027. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1028. let disposition = '';
  1029. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1030. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  1031. } else if (userAgent.indexOf('firefox') >= 0) {
  1032. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  1033. } else {
  1034. /* safari等其他非主流浏览器只能自求多福了 */
  1035. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  1036. }
  1037. ctx.response.set({
  1038. 'Content-Type': 'application/octet-stream',
  1039. 'Content-Disposition': disposition,
  1040. 'Content-Length': size,
  1041. });
  1042. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  1043. ctx.body = readStream;
  1044. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  1045. readStream.on('close', () => {
  1046. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1047. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1048. }
  1049. });
  1050. } catch (error) {
  1051. this.log(error);
  1052. }
  1053. }
  1054. /**
  1055. * 删除附件
  1056. * @param {Object} ctx - egg全局变量
  1057. * @return {void}
  1058. */
  1059. async deleteFile(ctx) {
  1060. const responseData = {
  1061. err: 0,
  1062. msg: '',
  1063. data: '',
  1064. };
  1065. try {
  1066. const data = JSON.parse(ctx.request.body.data);
  1067. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1068. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  1069. if (!fileInfo || !Object.keys(fileInfo).length) {
  1070. throw '该文件不存在';
  1071. }
  1072. if (!fileInfo.extra_upload && change.status === audit.flow.status.checked) {
  1073. throw '无权限删除';
  1074. }
  1075. if (fileInfo !== undefined && fileInfo !== '') {
  1076. // 先删除文件
  1077. await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  1078. // 再删除数据库
  1079. await ctx.service.changeAtt.deleteById(data.id);
  1080. responseData.data = '';
  1081. } else {
  1082. throw '不存在该文件';
  1083. }
  1084. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1085. // throw '参数有误';
  1086. // }
  1087. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1088. // responseData.data = { add: addCompany, select: selectCompany };
  1089. } catch (err) {
  1090. responseData.err = 1;
  1091. responseData.msg = err;
  1092. }
  1093. ctx.body = responseData;
  1094. }
  1095. /**
  1096. * 查看附件
  1097. * @param {Object} ctx - egg全局变量
  1098. * @return {void}
  1099. */
  1100. async checkFile(ctx) {
  1101. const responseData = { err: 0, msg: '' };
  1102. const id = parseInt(ctx.params.id);
  1103. if (id) {
  1104. try {
  1105. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1106. if (fileInfo && Object.keys(fileInfo).length) {
  1107. let filepath = fileInfo.filepath;
  1108. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  1109. filepath = `/change/download/file/${fileInfo.id}`;
  1110. } else {
  1111. filepath = filepath.replace(/^app|\/app/, '');
  1112. }
  1113. fileInfo.filepath && (responseData.data = { filepath });
  1114. }
  1115. } catch (error) {
  1116. this.log(error);
  1117. this.setMessage(error.toString(), this.messageType.ERROR);
  1118. responseData.err = 1;
  1119. responseData.msg = error.toString();
  1120. }
  1121. }
  1122. ctx.body = responseData;
  1123. }
  1124. /**
  1125. * 删除变更令
  1126. * @param {Object} ctx - egg全局变量
  1127. * @return {void}
  1128. */
  1129. async delete(ctx) {
  1130. try {
  1131. const result = await ctx.service.change.delete(ctx.request.body.cid);
  1132. if (!result) {
  1133. throw '删除变更令失败';
  1134. }
  1135. ctx.redirect(ctx.request.header.referer);
  1136. } catch (err) {
  1137. console.log(err);
  1138. ctx.redirect(ctx.request.header.referer);
  1139. }
  1140. }
  1141. /**
  1142. * 变更令重新审批
  1143. * @param {Object} ctx - egg全局变量
  1144. * @return {void}
  1145. */
  1146. async checkAgain(ctx) {
  1147. try {
  1148. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1149. if (!changeData) {
  1150. throw '变更令数据错误';
  1151. }
  1152. // 获取终审
  1153. const auditInfo = (await this.ctx.service.changeAudit.getAllDataByCondition({ where: { cid: changeData.cid }, orders: [['usort', 'desc']], limit: 1, offset: 0 }))[0];
  1154. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== auditInfo.uid) {
  1155. throw '您无权进行该操作';
  1156. }
  1157. if (ctx.session.sessionUser.loginStatus === 0) {
  1158. const code = ctx.request.body.code;
  1159. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1160. if (!pa.auth_mobile) {
  1161. throw '未绑定手机号';
  1162. }
  1163. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1164. const cacheCode = await app.redis.get(cacheKey);
  1165. // console.log(cacheCode);
  1166. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1167. throw '验证码不正确!';
  1168. }
  1169. }
  1170. // 获取是否已存在调用变更令
  1171. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, changeData.cid);
  1172. const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  1173. if (stageChangeNum !== 0) {
  1174. throw '该变更令已被调用,无法重新审批';
  1175. }
  1176. // 重新审批
  1177. const result = await ctx.service.change.checkAgain(changeData.cid);
  1178. if (!result) {
  1179. throw '重新审批失败';
  1180. }
  1181. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1182. ctx.body = {
  1183. err: 0,
  1184. url: ctx.request.header.referer,
  1185. msg: '',
  1186. };
  1187. } catch (err) {
  1188. console.log(err);
  1189. // ctx.redirect(ctx.request.header.referer);
  1190. ctx.body = {
  1191. err: 1,
  1192. // url: ctx.request.header.referer,
  1193. msg: err,
  1194. };
  1195. }
  1196. }
  1197. /**
  1198. * 获取变更清单
  1199. * @param ctx
  1200. * @return {Promise<void>}
  1201. */
  1202. async bills(ctx) {
  1203. try {
  1204. const data = JSON.parse(ctx.request.body.data);
  1205. const responseData = { err: 0, msg: '', data: [] };
  1206. switch (data.type) {
  1207. case 'gather':
  1208. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  1209. break;
  1210. default:
  1211. throw '查询的数据不存在';
  1212. }
  1213. ctx.body = responseData;
  1214. } catch (err) {
  1215. this.log(err);
  1216. this.ajaxErrorBody(err, '获取变更清单失败');
  1217. }
  1218. }
  1219. /**
  1220. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  1221. * @param ctx
  1222. * @return {Promise<void>}
  1223. */
  1224. async checkCodeRepeat(ctx) {
  1225. const responseData = {
  1226. err: 0,
  1227. msg: '',
  1228. data: '',
  1229. };
  1230. try {
  1231. const tenderId = ctx.params.id;
  1232. const cid = ctx.params.cid;
  1233. const data = JSON.parse(ctx.request.body.data);
  1234. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  1235. if (result) {
  1236. throw '该变更令号(批复编号)已使用';
  1237. }
  1238. } catch (err) {
  1239. responseData.err = 1;
  1240. responseData.msg = err;
  1241. }
  1242. ctx.body = responseData;
  1243. }
  1244. /**
  1245. * 拷贝其他变更令
  1246. * @param {object} ctx - 全局上下文
  1247. */
  1248. async copyChange(ctx) {
  1249. const responseData = {
  1250. err: 0,
  1251. msg: '',
  1252. data: '',
  1253. };
  1254. try {
  1255. const cid = ctx.params.cid;
  1256. const copy_cid = JSON.parse(ctx.request.body.data);
  1257. const result = await ctx.service.change.handleCopyChange(cid, copy_cid);
  1258. if (!result) {
  1259. responseData.err = 1;
  1260. responseData.msg = '拷贝失败!';
  1261. }
  1262. } catch (error) {
  1263. responseData.err = 1;
  1264. responseData.msg = error;
  1265. }
  1266. ctx.body = responseData;
  1267. }
  1268. }
  1269. return ChangeController;
  1270. };