change_controller.js 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  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 sorts = ctx.query.sort ? ctx.query.sort : 0;
  40. const orders = ctx.query.order ? ctx.query.order : 0;
  41. const changes = await ctx.service.change.getListByStatus(tender.id, status, 1, sorts, orders);
  42. const total = await ctx.service.change.getCountByStatus(tender.id, status);
  43. let page_total = 0;
  44. const tp = await ctx.service.change.getTp(tender.id, status);
  45. if (changes !== null) {
  46. let i = 0;
  47. for (const c of changes) {
  48. page_total = ctx.helper.add(page_total, c.total_price);
  49. const status = c.status === audit.flow.status.uncheck ? 0 : 1;
  50. // 根据审批人对当前变更令的状态取不同的展示方式。
  51. let changeAudit = '';
  52. let auditStatus = 0;
  53. switch (c.status) {
  54. case 1:
  55. auditStatus = 1;
  56. break;
  57. case 2:
  58. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  59. auditStatus = changeAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  60. break;
  61. case 3:
  62. case 4:
  63. auditStatus = 0;
  64. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  65. break;
  66. case 5:
  67. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times - 1, status);
  68. auditStatus = c.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  69. const back_changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, c.cid);
  70. c.stageChangeNum = this.ctx.helper.sum(back_changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  71. break;
  72. case 6:
  73. changeAudit = await ctx.service.changeAudit.getLastBackUser(c.cid, c.times);
  74. const checkingAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  75. auditStatus = checkingAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  76. break;
  77. case 9:
  78. auditStatus = 9;
  79. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, c.cid);
  80. c.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  81. break;
  82. default:
  83. break;
  84. }
  85. changes[i].changeAudit = changeAudit;
  86. changes[i].auditStatus = auditStatus;
  87. i++;
  88. }
  89. }
  90. // 分页相关
  91. const pageInfo = {
  92. page,
  93. total: Math.ceil(total / app.config.pageSize),
  94. queryData: JSON.stringify(ctx.urlInfo.query),
  95. };
  96. const filter = JSON.parse(JSON.stringify(audit.filter));
  97. filter.count = [];
  98. 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);
  99. 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);
  100. 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);
  101. 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);
  102. 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);
  103. const codeRule = tender.c_rule ? JSON.parse(tender.c_rule) : [];
  104. for (const rule of codeRule) {
  105. switch (rule.rule_type) {
  106. case codeRuleConst.measure.ruleType.dealCode:
  107. rule.preview = ctx.tender.info.deal_info.dealCode;
  108. break;
  109. case codeRuleConst.measure.ruleType.tenderName:
  110. rule.preview = tender.name;
  111. break;
  112. case codeRuleConst.measure.ruleType.inDate:
  113. rule.preview = moment().format('YYYY');
  114. break;
  115. case codeRuleConst.measure.ruleType.text:
  116. rule.preview = rule.text;
  117. break;
  118. case codeRuleConst.measure.ruleType.addNo:
  119. const s = '0000000000';
  120. rule.preview = s.substr(s.length - rule.format);
  121. break;
  122. default: break;
  123. }
  124. }
  125. const renderData = {
  126. uid: ctx.session.sessionUser.accountId,
  127. moment,
  128. tender,
  129. // tenderList,
  130. pageInfo,
  131. changes,
  132. page_total,
  133. tp,
  134. filter,
  135. status,
  136. codeRule,
  137. dealCode: ctx.tender.info.deal_info.dealCode,
  138. auditConst: audit.flow,
  139. changeConst,
  140. ruleType: codeRuleConst.ruleType.change,
  141. ruleConst: codeRuleConst.measure,
  142. tenderMenu: this.menu.tenderMenu,
  143. preUrl: '/tender/' + tenderId,
  144. tpUnit: ctx.tender.info.decimal.tp,
  145. };
  146. await this.layout('change/index.ejs', renderData, 'change/modal.ejs');
  147. }
  148. /**
  149. * 变更管理 页面 (Get)
  150. *
  151. * @param {Object} ctx - egg全局变量
  152. * @return {void}
  153. */
  154. async index(ctx) {
  155. try {
  156. await this._filterChanges(ctx);
  157. } catch (err) {
  158. this.log(err);
  159. ctx.redirect('/dashboard');
  160. }
  161. }
  162. /**
  163. *
  164. * @param {Object} ctx - egg全局变量
  165. * @return {void}
  166. */
  167. async newCode(ctx) {
  168. const responseData = {
  169. err: 0,
  170. msg: '',
  171. data: '',
  172. };
  173. try {
  174. const tenderId = ctx.params.id;
  175. if (!tenderId) {
  176. throw '当前未打开标段';
  177. }
  178. const tenderData = await ctx.service.tender.getDataById(tenderId);
  179. const cCodeRule = tenderData.c_rule !== null ? JSON.parse(tenderData.c_rule) : [];
  180. const code = [];
  181. for (const rule of cCodeRule) {
  182. switch (rule.rule_type) {
  183. case codeRuleConst.measure.ruleType.dealCode:
  184. code.push(ctx.tender.info.deal_info.dealCode);
  185. break;
  186. case codeRuleConst.measure.ruleType.tenderName:
  187. code.push(tenderData.name);
  188. break;
  189. case codeRuleConst.measure.ruleType.text:
  190. code.push(rule.text);
  191. break;
  192. case codeRuleConst.measure.ruleType.inDate:
  193. code.push(moment().format('YYYY'));
  194. break;
  195. case codeRuleConst.measure.ruleType.addNo:
  196. let s = '0000000000';
  197. const count = rule.start + await ctx.service.change.count({ tid: tenderId });
  198. s = s + count;
  199. code.push(s.substr(s.length - rule.format));
  200. break;
  201. default: break;
  202. }
  203. }
  204. responseData.data = code.join(tenderData.c_connector !== null && tenderData.c_connector !== 3 ? codeRuleConst.measure.connectorString[tenderData.c_connector] : '');
  205. } catch (err) {
  206. responseData.err = 1;
  207. responseData.msg = err;
  208. }
  209. ctx.body = responseData;
  210. }
  211. /**
  212. * 新增变更 (Post)
  213. *
  214. * @param {Object} ctx - egg全局变量
  215. * @return {void}
  216. */
  217. async add(ctx) {
  218. try {
  219. const tenderId = ctx.params.id;
  220. if (!tenderId) {
  221. throw '当前未打开标段';
  222. }
  223. const data = JSON.parse(ctx.request.body.data);
  224. if (!data.code || data.code === '' || !data.name || data.name === '') {
  225. throw '变更令号不能为空';
  226. }
  227. const change = await ctx.service.change.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  228. ctx.body = { err: 0, msg: '', data: change };
  229. } catch (err) {
  230. this.log(err);
  231. ctx.body = { err: 1, msg: err.toString() };
  232. }
  233. }
  234. /**
  235. * 变更管理 状态筛选 页面 (Get)
  236. * @param {Object} ctx - egg全局变量
  237. * @return {void}
  238. */
  239. async status(ctx) {
  240. try {
  241. const status = parseInt(ctx.params.status);
  242. await this._filterChanges(ctx, status);
  243. } catch (err) {
  244. this.logger.error(err);
  245. ctx.redirect('/tender/' + ctx.params.id + '/change');
  246. }
  247. }
  248. /**
  249. * 变更信息 页面 (Get)
  250. *
  251. * @param {Object} ctx - egg全局变量
  252. * @return {void}
  253. */
  254. async info(ctx) {
  255. try {
  256. const whiteList = this.ctx.app.config.multipart.whitelist;
  257. const tenderid = ctx.params.id !== undefined ? ctx.params.id : ctx.session.sessionUser.tenderId;
  258. ctx.session.sessionUser.tenderId = tenderid;
  259. const tender = await ctx.service.tender.getDataById(tenderid);
  260. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  261. // 后台判断当前人查看info状态
  262. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  263. // 获取附件列表
  264. const attList = await ctx.service.changeAtt.getChangeAttachment(ctx.params.cid);
  265. // 获取其他变更令数据
  266. const othersChange = await ctx.service.change.getOthersChange(ctx.params.id, ctx.params.cid);
  267. // 根据auditStatus获取审批人列表
  268. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  269. // 获取已选清单
  270. let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  271. // 获取用户人验证手机号
  272. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  273. const auth_mobile = pa.auth_mobile;
  274. const renderData = {
  275. uid: ctx.session.sessionUser.accountId,
  276. tender,
  277. change,
  278. othersChange,
  279. changeConst,
  280. auditStatus,
  281. auditConst: audit.flow,
  282. ledgerConsts: audit.ledger.status,
  283. attList,
  284. whiteList,
  285. auditList,
  286. changeList,
  287. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  288. upUnit: ctx.tender.info.decimal.up,
  289. authMobile: auth_mobile,
  290. shenpiConst,
  291. };
  292. // 根据auditStatus状态获取的不同的数据
  293. if (auditStatus === 1 || auditStatus === 2 || auditStatus === 9) {
  294. renderData.changeUnits = changeConst.units;
  295. renderData.precision = ctx.tender.info.precision;
  296. // renderData.accountGroup = accountGroup;
  297. // 获取所有项目参与者
  298. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  299. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  300. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  301. });
  302. renderData.accountList = accountList;
  303. renderData.accountGroup = accountGroup.map((item, idx) => {
  304. const groupList = accountList.filter(item => item.account_group === idx);
  305. return { groupName: item, groupList };
  306. });
  307. // 重新上报获取审批流程
  308. if (auditStatus === 2 || auditStatus === 9) {
  309. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  310. // 展示页右侧审批流程列表
  311. const auditList3 = [];
  312. for (let time = 1; time <= change.times - 1; time++) {
  313. const auditTimeList = [];
  314. let max_sort = 1;
  315. for (const al of auditList2) {
  316. if (al.times === time) {
  317. auditTimeList.push(al);
  318. if (al.usite > max_sort) {
  319. max_sort = al.usite;
  320. }
  321. }
  322. }
  323. for (const i in auditTimeList) {
  324. auditTimeList[i].max_sort = max_sort;
  325. }
  326. auditList3.push(auditTimeList);
  327. }
  328. renderData.auditList3 = auditList3;
  329. }
  330. // 根据清单获取提交数据和计算总金额
  331. const changeListData = [];
  332. const changeWhiteListData = [];
  333. let ototalCost = 0;
  334. let ctotalCost = 0;
  335. for (const cl of changeList) {
  336. const cLArray = [
  337. cl.code,
  338. cl.name,
  339. cl.bwmx,
  340. cl.unit,
  341. cl.unit_price,
  342. cl.oamount,
  343. cl.camount,
  344. cl.detail,
  345. cl.lid,
  346. cl.xmj_code,
  347. cl.xmj_jldy,
  348. cl.gcl_id,
  349. ];
  350. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, ctx.tender.info.decimal.tp);
  351. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, ctx.tender.info.decimal.tp);
  352. if (cl.lid !== '0') {
  353. changeListData.push(cLArray.join('*;*'));
  354. } else {
  355. changeWhiteListData.push(cLArray.join('*;*'));
  356. }
  357. }
  358. renderData.changeListData = changeListData.join('^_^');
  359. renderData.changeWhiteListData = changeWhiteListData.join('^_^');
  360. renderData.ototalCost = ototalCost;
  361. renderData.ctotalCost = ctotalCost;
  362. // 获取公司列表
  363. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: tenderid } });
  364. renderData.companyList = companyList;
  365. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7) {
  366. // 展示页左侧审批流程列表和清单审批列表数据
  367. const times = change.status === audit.flow.status.back ?
  368. change.times - 1 : change.times;
  369. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  370. // 展示页右侧审批流程列表
  371. const auditList3 = [];
  372. for (let time = 1; time <= times; time++) {
  373. const auditTimeList = [];
  374. let max_sort = 1;
  375. for (const al of auditList) {
  376. if (al.times === time) {
  377. auditTimeList.push(al);
  378. if (al.usite > max_sort) {
  379. max_sort = al.usite;
  380. }
  381. }
  382. }
  383. for (const i in auditTimeList) {
  384. auditTimeList[i].max_sort = max_sort;
  385. }
  386. auditList3.push(auditTimeList);
  387. }
  388. renderData.auditList3 = auditList3;
  389. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  390. renderData.changeList = changeList;
  391. let ototalCost = 0;
  392. let ctotalCost = 0;
  393. let stotalCost = 0;
  394. const auditTotalCost = [];
  395. for (const cl of changeList) {
  396. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  397. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  398. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  399. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  400. // stotalCost += cl.samount !== '' && cl.unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.samount), renderData.tpUnit)) : 0;
  401. stotalCost += cl.samount !== '' && cl.unit_price !== null ? ctx.helper.mul(cl.unit_price, cl.samount, renderData.tpUnit) : 0;
  402. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  403. auditTotalCost.push(audit_amount);
  404. }
  405. renderData.ototalCost = ototalCost;
  406. renderData.ctotalCost = ctotalCost;
  407. renderData.stotalCost = stotalCost;
  408. // 清单表页赋值
  409. for (const [index, au] of auditList2.entries()) {
  410. if (au.usite !== 0) {
  411. au.list_amount = [];
  412. au.totalCost = 0;
  413. for (const [auindex, at] of auditTotalCost.entries()) {
  414. au.list_amount.push(at[index - 1]);
  415. // 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;
  416. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  417. }
  418. }
  419. }
  420. renderData.auditList2 = auditList2;
  421. } else if (auditStatus === 6) {
  422. // 展示页左侧审批流程列表和清单审批列表数据
  423. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  424. renderData.auditList2 = auditList2;
  425. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  426. for (const i in auditList3) {
  427. auditList3[i].max_sort = auditList2.length - 1;
  428. }
  429. renderData.auditList3 = auditList3;
  430. // 展示页右侧审批流程列表
  431. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  432. const auditList4 = [];
  433. for (let time = 1; time <= change.times; time++) {
  434. const auditTimeList = [];
  435. let max_sort = 1;
  436. for (const al of auditList5) {
  437. if (al.times === time) {
  438. auditTimeList.push(al);
  439. if (al.usite > max_sort) {
  440. max_sort = al.usite;
  441. }
  442. }
  443. }
  444. for (const i in auditTimeList) {
  445. auditTimeList[i].max_sort = max_sort;
  446. }
  447. if (auditTimeList.length > 0) {
  448. auditList4.push(auditTimeList);
  449. }
  450. }
  451. renderData.auditList4 = auditList4;
  452. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  453. renderData.changeList = changeList;
  454. let ototalCost = 0;
  455. let ctotalCost = 0;
  456. const auditTotalCost = [];
  457. const auditUnit = [];
  458. for (const cl of changeList) {
  459. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  460. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  461. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  462. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  463. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  464. auditTotalCost.push(audit_amount);
  465. }
  466. renderData.ototalCost = ototalCost;
  467. renderData.ctotalCost = ctotalCost;
  468. // 清单表页赋值
  469. for (const [index, au] of auditList.entries()) {
  470. if (au.usite !== 0) {
  471. au.list_amount = [];
  472. au.totalCost = 0;
  473. if (au.uid === renderData.uid) {
  474. for (const [auindex, at] of auditTotalCost.entries()) {
  475. // if (at[index - 2] !== undefined) {
  476. // au.list_amount.push(at[index - 2]);
  477. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 2]), renderData.tpUnit));
  478. // } else if (at[index - 2] === undefined) {
  479. // au.list_amount.push(changeList[auindex].camount);
  480. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].camount), renderData.tpUnit));
  481. // }
  482. au.list_amount.push(changeList[auindex].spamount);
  483. // au.totalCost += changeList[auindex].unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].spamount), renderData.tpUnit));
  484. au.totalCost += changeList[auindex].unit_price === null ? 0 : ctx.helper.mul(changeList[auindex].unit_price, changeList[auindex].spamount, renderData.tpUnit);
  485. }
  486. } else {
  487. for (const [auindex, at] of auditTotalCost.entries()) {
  488. au.list_amount.push(at[index - 1]);
  489. // 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;
  490. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  491. }
  492. }
  493. }
  494. }
  495. }
  496. renderData.auditList = auditList;
  497. // 获取是否已存在调用变更令
  498. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  499. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  500. await this.layout('change/info.ejs', renderData, 'change/info_modal.ejs');
  501. } catch (err) {
  502. this.log(err);
  503. ctx.redirect('/tender/' + ctx.params.id + '/change');
  504. }
  505. }
  506. /**
  507. * 变更信息 新版本页面 (Get)
  508. *
  509. * @param {Object} ctx - egg全局变量
  510. * @return {void}
  511. */
  512. async information(ctx) {
  513. try {
  514. const whiteList = this.ctx.app.config.multipart.whitelist;
  515. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  516. const change = ctx.change;
  517. // 后台判断当前人查看info状态
  518. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  519. // 获取附件列表
  520. const attList = await ctx.service.changeAtt.getChangeAttachment(change.cid, 'desc');
  521. // 获取其他变更令数据
  522. const othersChange = await ctx.service.change.getOthersChange(ctx.tender.id, change.cid);
  523. // 根据auditStatus获取审批人列表
  524. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  525. // 获取用户人验证手机号
  526. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  527. const auth_mobile = pa.auth_mobile;
  528. const renderData = {
  529. tender,
  530. change,
  531. othersChange,
  532. changeConst,
  533. auditStatus,
  534. auditConst: audit.flow,
  535. ledgerConsts: audit.ledger.status,
  536. attList,
  537. whiteList,
  538. auditList,
  539. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  540. upUnit: ctx.tender.info.decimal.up,
  541. authMobile: auth_mobile,
  542. shenpiConst,
  543. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.information),
  544. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  545. precision: ctx.tender.info.precision,
  546. };
  547. // 根据auditStatus状态获取的不同的数据
  548. if (auditStatus === 1 || auditStatus === 2 || auditStatus === 9) {
  549. renderData.changeUnits = changeConst.units;
  550. // renderData.accountGroup = accountGroup;
  551. // 获取所有项目参与者
  552. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  553. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  554. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  555. });
  556. renderData.accountList = accountList;
  557. renderData.accountGroup = accountGroup.map((item, idx) => {
  558. const groupList = accountList.filter(item => item.account_group === idx);
  559. return { groupName: item, groupList };
  560. });
  561. // 重新上报获取审批流程
  562. if (auditStatus === 2 || auditStatus === 9) {
  563. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  564. // 展示页右侧审批流程列表
  565. const auditList3 = [];
  566. for (let time = 1; time <= change.times - 1; time++) {
  567. const auditTimeList = [];
  568. let max_sort = 1;
  569. for (const al of auditList2) {
  570. if (al.times === time) {
  571. auditTimeList.push(al);
  572. if (al.usite > max_sort) {
  573. max_sort = al.usite;
  574. }
  575. }
  576. }
  577. for (const i in auditTimeList) {
  578. auditTimeList[i].max_sort = max_sort;
  579. }
  580. auditList3.push(auditTimeList);
  581. }
  582. renderData.auditList3 = auditList3;
  583. }
  584. // 获取公司列表
  585. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  586. renderData.companyList = companyList;
  587. // 获取已选清单
  588. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  589. renderData.changeList = changeList;
  590. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7 || auditStatus === 8) {
  591. // 展示页左侧审批流程列表和清单审批列表数据
  592. const times = change.status === audit.flow.status.back ?
  593. change.times - 1 : change.times;
  594. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  595. // 展示页右侧审批流程列表
  596. const auditList3 = [];
  597. for (let time = 1; time <= times; time++) {
  598. const auditTimeList = [];
  599. let max_sort = 1;
  600. for (const al of auditList) {
  601. if (al.times === time) {
  602. auditTimeList.push(al);
  603. if (al.usite > max_sort) {
  604. max_sort = al.usite;
  605. }
  606. }
  607. }
  608. for (const i in auditTimeList) {
  609. auditTimeList[i].max_sort = max_sort;
  610. }
  611. auditList3.push(auditTimeList);
  612. }
  613. renderData.auditList3 = auditList3;
  614. // 获取已选清单
  615. // let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  616. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  617. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  618. for (const cl of changeList) {
  619. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  620. // 清单表页赋值
  621. for (const [index, au] of auditList2.entries()) {
  622. if (au.usite !== 0) {
  623. cl['audit_amount_' + au.uid] = audit_amount[index - 1] ? audit_amount[index - 1] : null;
  624. }
  625. }
  626. }
  627. renderData.changeList = changeList;
  628. renderData.auditList2 = auditList2;
  629. } else if (auditStatus === 6) {
  630. // 展示页左侧审批流程列表和清单审批列表数据
  631. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  632. renderData.auditList2 = auditList2;
  633. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  634. for (const i in auditList3) {
  635. auditList3[i].max_sort = auditList2.length - 1;
  636. }
  637. renderData.auditList3 = auditList3;
  638. // 展示页右侧审批流程列表
  639. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  640. const auditList4 = [];
  641. for (let time = 1; time <= change.times; time++) {
  642. const auditTimeList = [];
  643. let max_sort = 1;
  644. for (const al of auditList5) {
  645. if (al.times === time) {
  646. auditTimeList.push(al);
  647. if (al.usite > max_sort) {
  648. max_sort = al.usite;
  649. }
  650. }
  651. }
  652. for (const i in auditTimeList) {
  653. auditTimeList[i].max_sort = max_sort;
  654. }
  655. if (auditTimeList.length > 0) {
  656. auditList4.push(auditTimeList);
  657. }
  658. }
  659. renderData.auditList4 = auditList4;
  660. // 获取已选清单
  661. // let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  662. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  663. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  664. for (const cl of changeList) {
  665. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  666. // 清单表页赋值
  667. for (const [index, au] of auditList2.entries()) {
  668. if (au.usite !== 0) {
  669. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  670. }
  671. }
  672. }
  673. renderData.changeList = changeList;
  674. }
  675. renderData.auditList = auditList;
  676. // 获取是否已存在调用变更令
  677. let changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  678. changeUsedData = ctx.helper._.filter(changeUsedData, function(item) {
  679. return item.used_qty !== null;
  680. })
  681. renderData.changeUsedData = changeUsedData;
  682. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  683. await this.layout('change/information.ejs', renderData, 'change/information_modal.ejs');
  684. } catch (err) {
  685. this.log(err);
  686. ctx.redirect('/tender/' + ctx.params.id + '/change');
  687. }
  688. }
  689. /**
  690. * 变更清单 - 操作 (Ajax)
  691. * @param ctx
  692. * @return {Promise<void>}
  693. */
  694. async saveListsData(ctx) {
  695. try {
  696. const data = JSON.parse(ctx.request.body.data);
  697. const responseData = {
  698. err: 0,
  699. msg: '',
  700. data: {},
  701. };
  702. switch (data.type) {
  703. case 'add':
  704. responseData.data = await ctx.service.changeAuditList.add(data.postData);
  705. break;
  706. case 'batchadd':
  707. responseData.data = await ctx.service.changeAuditList.batchAdd(data);
  708. break;
  709. case 'del':
  710. await ctx.service.changeAuditList.del(data.id);
  711. break;
  712. case 'update':
  713. await ctx.service.changeAuditList.save(data.updateData);
  714. break;
  715. case 'paste':
  716. await ctx.service.changeAuditList.saveDatas(data.updateData);
  717. // 取所有工料表
  718. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  719. break;
  720. case 'ledger_list':
  721. await ctx.service.changeAuditList.saveLedgerListDatas(data.updateData);
  722. // 取所有工料表
  723. responseData.data = { changeList: await ctx.service.changeAuditList.getList(ctx.change.cid),
  724. usedList: await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, ctx.change.cid) };
  725. break;
  726. case 'remove_list':
  727. await ctx.service.changeAuditList.removeLedgerListDatas(data.updateData);
  728. // 取所有工料表
  729. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  730. break;
  731. case 'info':
  732. await ctx.service.change.saveInfo(data.updateData);
  733. // 取所有工料表
  734. responseData.data = '保存成功';
  735. break;
  736. case 'paste_amount_rows':
  737. await ctx.service.changeAuditList.saveDatas(data.updateData);
  738. let changeList = await ctx.service.changeAuditList.getList(ctx.change.cid);
  739. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times);
  740. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  741. for (const cl of changeList) {
  742. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  743. // 清单表页赋值
  744. for (const [index, au] of auditList2.entries()) {
  745. if (au.usite !== 0) {
  746. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  747. }
  748. }
  749. }
  750. // 取所有工料表
  751. responseData.data = changeList;
  752. break;
  753. default: throw '参数有误';
  754. }
  755. ctx.body = responseData;
  756. } catch (err) {
  757. this.log(err);
  758. ctx.body = { err: 1, msg: err.toString(), data: null };
  759. }
  760. }
  761. /**
  762. * 上报和重新上报
  763. * @param ctx
  764. * @return {Promise<void>}
  765. */
  766. async startAudit(ctx) {
  767. try {
  768. // 检查权限等
  769. if (!ctx.change) {
  770. throw '数据错误';
  771. }
  772. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  773. throw '您无权上报该变更令数据';
  774. }
  775. if (!(ctx.change.status === audit.flow.status.uncheck || ctx.change.status === audit.flow.status.back || ctx.change.status === audit.flow.status.revise)) {
  776. throw '该变更令当前无法上报';
  777. }
  778. // 判断是否是修订,判断有无审批人员作弊
  779. if ((ctx.change.status === audit.flow.status.revise || ctx.change.is_revise) && ctx.tender.info.shenpi.change === shenpiConst.sp_status.sqspr) {
  780. // 获取上一次的审批人流程
  781. const lastUserList = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times - 1);
  782. const lastUidList = ctx.helper._.map(lastUserList, 'uid');
  783. // 判断上一次审批是否为非原报为审批人
  784. const nowUidList = ctx.helper._.map(ctx.change.auditors, 'uid');
  785. // 判断条件修订可上报条件
  786. // 1.有原报,有其他人 可以添加原报作为审核人,但是不能只原报上报
  787. // 2.有原报,无其他人 可以添加原报作为审核人,可以只原报上报
  788. // 3.无原报,有其他人 不可以添加原报
  789. const noYBUidList = ctx.change.status === audit.flow.status.revise ? ctx.helper._.initial(ctx.helper._.tail(lastUidList)) : ctx.helper._.tail(lastUidList);
  790. if (!ctx.helper._.isEqual(lastUidList, nowUidList) && ctx.helper._.includes(noYBUidList, lastUidList[0]) && nowUidList.length === 2 && nowUidList[0] === nowUidList[1]) {
  791. throw '该变更令不能指定原报人为单独审批人';
  792. }
  793. if (!ctx.helper._.isEqual(lastUidList, nowUidList) && !ctx.helper._.includes(noYBUidList, lastUidList[0]) && ctx.helper._.includes(ctx.helper._.tail(nowUidList), nowUidList[0])) {
  794. throw '该变更令不能指定原报为审批人,请移除';
  795. }
  796. }
  797. await ctx.service.changeAudit.start(ctx.change.cid, ctx.change.times);
  798. ctx.redirect(ctx.request.header.referer);
  799. } catch (err) {
  800. this.log(err);
  801. ctx.session.postError = err.toString();
  802. ctx.redirect(ctx.request.header.referer);
  803. }
  804. }
  805. // 审批相关
  806. /**
  807. * 添加审批人
  808. * @param ctx
  809. * @return {Promise<void>}
  810. */
  811. async addAudit(ctx) {
  812. try {
  813. const data = JSON.parse(ctx.request.body.data);
  814. const id = this.app._.toInteger(data.auditorId);
  815. if (isNaN(id) || id <= 0) {
  816. throw '参数错误';
  817. }
  818. // 检查权限等
  819. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  820. throw '您无权添加审核人';
  821. }
  822. if (ctx.change.status === audit.flow.status.checking || ctx.change.status === audit.flow.status.checked) {
  823. throw '当前不允许添加审核人';
  824. }
  825. const auditorList = await ctx.service.changeAudit.getAuditors(ctx.change.cid, ctx.change.times);
  826. // 检查审核人是否已存在
  827. const exist = this.app._.find(auditorList, { uid: id });
  828. if (exist) {
  829. throw '该审核人已存在,请勿重复添加';
  830. }
  831. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdzs });
  832. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs ? 1 : 0;
  833. const result = await ctx.service.changeAudit.addAuditor(ctx.change.cid, id, ctx.change.times, is_gdzs);
  834. if (!result) {
  835. throw '添加审核人失败';
  836. }
  837. // const auditors = await ctx.service.changeAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  838. const auditors = null;
  839. ctx.body = { err: 0, msg: '', data: auditors };
  840. } catch (err) {
  841. this.log(err);
  842. ctx.body = { err: 1, msg: err.toString(), data: null };
  843. }
  844. }
  845. /**
  846. * 移除审批人
  847. * @param ctx
  848. * @return {Promise<void>}
  849. */
  850. async deleteAudit(ctx) {
  851. try {
  852. const data = JSON.parse(ctx.request.body.data);
  853. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  854. if (isNaN(id) || id <= 0) {
  855. throw '参数错误';
  856. }
  857. const result = await ctx.service.changeAudit.deleteAuditor(ctx.change.cid, id, ctx.change.times);
  858. if (!result) {
  859. throw '移除审核人失败';
  860. }
  861. const auditors = null;
  862. ctx.body = { err: 0, msg: '', data: auditors };
  863. } catch (err) {
  864. ctx.body = { err: 1, msg: err.toString(), data: null };
  865. }
  866. }
  867. async defaultBills(ctx) {
  868. try {
  869. const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  870. const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  871. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  872. ctx.body = { err: 0, msg: '', data: { bills: ledgerData, pos: posData, dealBills } };
  873. } catch (err) {
  874. this.log(err);
  875. ctx.body = { err: 1, msg: err.toString(), data: [] };
  876. }
  877. }
  878. /**
  879. * 变更令上报和保存
  880. * @param {Object} ctx - egg全局变量
  881. * @return {void}
  882. */
  883. async save(ctx) {
  884. // 变更令信息
  885. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  886. try {
  887. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  888. if (!result) {
  889. throw '上报失败';
  890. }
  891. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  892. ctx.body = { err: 0, msg: '保存成功' };
  893. } else {
  894. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  895. }
  896. } catch (err) {
  897. this.log(err);
  898. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  899. ctx.body = { err: 1, msg: err.toString() };
  900. } else {
  901. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  902. }
  903. }
  904. }
  905. /**
  906. * 变更令审批
  907. * @param {Object} ctx - egg全局变量
  908. * @return {void}
  909. */
  910. async approval(ctx) {
  911. try {
  912. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.change_id });
  913. if (!changeData) {
  914. throw '变更令数据错误';
  915. }
  916. const status = parseInt(ctx.request.body.status);
  917. let result = false;
  918. const pid = this.ctx.session.sessionProject.id;
  919. switch (status) {
  920. case 3:// 审批通过
  921. result = await ctx.service.change.approvalSuccess(pid, ctx.request.body, changeData);
  922. break;
  923. case 4:// 审批终止
  924. result = await ctx.service.change.approvalStop(ctx.request.body);
  925. break;
  926. case 5:// 审批退回到原报人
  927. result = await ctx.service.change.approvalBack(pid, ctx.request.body, changeData);
  928. break;
  929. case 6:// 审批退回到上一个审批人
  930. result = await ctx.service.change.approvalBackNew(pid, ctx.request.body, changeData);
  931. break;
  932. default:break;
  933. }
  934. if (!result) {
  935. throw '审批失败';
  936. }
  937. ctx.redirect(ctx.request.header.referer);
  938. } catch (err) {
  939. console.log(err);
  940. ctx.redirect(ctx.request.header.referer);
  941. }
  942. }
  943. /**
  944. * 变更公司管理
  945. * @param {Object} ctx - egg全局变量
  946. * @return {void}
  947. */
  948. async updateCompany(ctx) {
  949. const responseData = {
  950. err: 0,
  951. msg: '',
  952. data: '',
  953. };
  954. try {
  955. const data = JSON.parse(ctx.request.body.data);
  956. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  957. throw '参数有误';
  958. }
  959. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  960. responseData.data = { add: addCompany, select: selectCompany };
  961. } catch (err) {
  962. responseData.err = 1;
  963. responseData.msg = err;
  964. }
  965. ctx.body = responseData;
  966. }
  967. /**
  968. * 上传附件
  969. * @param {Object} ctx - egg全局变量
  970. * @return {void}
  971. */
  972. async uploadFile(ctx) {
  973. const responseData = {
  974. err: 0,
  975. msg: '',
  976. data: [],
  977. };
  978. let stream;
  979. try {
  980. const parts = ctx.multipart({ autoFields: true });
  981. const files = [];
  982. let index = 0;
  983. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  984. const extra_upload = change.status === audit.flow.status.checked;
  985. while ((stream = await parts()) !== undefined) {
  986. // 判断用户是否选择上传文件
  987. if (!stream.filename) {
  988. throw '请选择上传的文件!';
  989. }
  990. // const create_time = Date.parse(new Date()) / 1000;
  991. // const fileInfo = path.parse(stream.filename);
  992. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  993. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  994. // // 判断文件夹是否存在,不存在则直接创建文件夹
  995. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  996. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  997. // }
  998. // // 保存文件
  999. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  1000. const fileInfo = path.parse(stream.filename);
  1001. const create_time = Date.parse(new Date()) / 1000;
  1002. const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  1003. await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  1004. await sendToWormhole(stream);
  1005. // 保存数据到att表
  1006. const fileData = {
  1007. in_time: create_time,
  1008. filename: fileInfo.name,
  1009. fileext: fileInfo.ext,
  1010. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  1011. filepath,
  1012. extra_upload,
  1013. };
  1014. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  1015. if (!result) {
  1016. throw '导入数据库保存失败';
  1017. }
  1018. // fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  1019. // fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  1020. fileData.uid = ctx.session.sessionUser.accountId;
  1021. fileData.id = result.insertId;
  1022. delete fileData.filepath;
  1023. files.push(fileData);
  1024. ++index;
  1025. }
  1026. responseData.data = files;
  1027. } catch (err) {
  1028. this.log(err);
  1029. // 失败需要消耗掉stream 以防卡死
  1030. if (stream) {
  1031. await sendToWormhole(stream);
  1032. }
  1033. this.setMessage(err.toString(), this.messageType.ERROR);
  1034. }
  1035. ctx.body = responseData;
  1036. }
  1037. /**
  1038. * 下载附件
  1039. * @param {Object} ctx - egg全局变量
  1040. * @return {void}
  1041. */
  1042. async downloadFile(ctx) {
  1043. const id = ctx.params.id;
  1044. if (id) {
  1045. try {
  1046. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1047. if (fileInfo !== undefined && fileInfo !== '') {
  1048. const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  1049. // 解决中文无法下载问题
  1050. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1051. let disposition = '';
  1052. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1053. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  1054. } else if (userAgent.indexOf('firefox') >= 0) {
  1055. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  1056. } else {
  1057. /* safari等其他非主流浏览器只能自求多福了 */
  1058. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  1059. }
  1060. ctx.response.set({
  1061. 'Content-Type': 'application/octet-stream',
  1062. 'Content-Disposition': disposition,
  1063. 'Content-Length': fileInfo.filesize,
  1064. });
  1065. ctx.body = await fs.createReadStream(fileName);
  1066. } else {
  1067. throw '不存在该文件';
  1068. }
  1069. } catch (err) {
  1070. this.log(err);
  1071. this.setMessage(err.toString(), this.messageType.ERROR);
  1072. }
  1073. }
  1074. }
  1075. /**
  1076. * 批量下载 - 压缩成zip文件返回
  1077. * @param {Oject} ctx - 全局上下文
  1078. */
  1079. async downloadZip(ctx) {
  1080. const time = Date.now();
  1081. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  1082. const responseData = {
  1083. err: 0,
  1084. msg: '',
  1085. };
  1086. try {
  1087. // const fileIds = JSON.parse(ctx.request.query.fileIds);
  1088. const { fileIds = [] } = JSON.parse(ctx.request.body.data);
  1089. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  1090. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  1091. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  1092. // 解决中文无法下载问题
  1093. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1094. let disposition = '';
  1095. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1096. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  1097. } else if (userAgent.indexOf('firefox') >= 0) {
  1098. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  1099. } else {
  1100. /* safari等其他非主流浏览器只能自求多福了 */
  1101. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  1102. }
  1103. ctx.response.set({
  1104. 'Content-Type': 'application/octet-stream',
  1105. 'Content-Disposition': disposition,
  1106. 'Content-Length': size,
  1107. });
  1108. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  1109. ctx.body = readStream;
  1110. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  1111. readStream.on('close', () => {
  1112. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1113. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1114. }
  1115. });
  1116. // fs的错误不能被try catch捕捉
  1117. readStream.on('error', err => {
  1118. this.log(err);
  1119. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1120. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1121. }
  1122. responseData.err = 1;
  1123. responseData.msg = err.toString();
  1124. ctx.body = responseData;
  1125. });
  1126. } catch (err) {
  1127. this.log(err);
  1128. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1129. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1130. }
  1131. this.setMessage(err.toString(), this.messageType.ERROR);
  1132. responseData.err = 1;
  1133. responseData.msg = err.toString();
  1134. ctx.body = responseData;
  1135. }
  1136. }
  1137. /**
  1138. * 删除附件
  1139. * @param {Object} ctx - egg全局变量
  1140. * @return {void}
  1141. */
  1142. async deleteFile(ctx) {
  1143. const responseData = {
  1144. err: 0,
  1145. msg: '',
  1146. data: '',
  1147. };
  1148. try {
  1149. const data = JSON.parse(ctx.request.body.data);
  1150. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1151. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  1152. if (!fileInfo || !Object.keys(fileInfo).length) {
  1153. throw '该文件不存在';
  1154. }
  1155. if (!fileInfo.extra_upload && change.status === audit.flow.status.checked) {
  1156. throw '无权限删除';
  1157. }
  1158. if (fileInfo !== undefined && fileInfo !== '') {
  1159. // 先删除文件
  1160. await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  1161. // 再删除数据库
  1162. await ctx.service.changeAtt.deleteById(data.id);
  1163. responseData.data = '';
  1164. } else {
  1165. throw '不存在该文件';
  1166. }
  1167. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1168. // throw '参数有误';
  1169. // }
  1170. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1171. // responseData.data = { add: addCompany, select: selectCompany };
  1172. } catch (err) {
  1173. responseData.err = 1;
  1174. responseData.msg = err;
  1175. }
  1176. ctx.body = responseData;
  1177. }
  1178. /**
  1179. * 查看附件
  1180. * @param {Object} ctx - egg全局变量
  1181. * @return {void}
  1182. */
  1183. async checkFile(ctx) {
  1184. const responseData = { err: 0, msg: '' };
  1185. const id = parseInt(ctx.params.id);
  1186. if (id) {
  1187. try {
  1188. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1189. if (fileInfo && Object.keys(fileInfo).length) {
  1190. let filepath = fileInfo.filepath;
  1191. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  1192. filepath = `/change/download/file/${fileInfo.id}`;
  1193. } else {
  1194. filepath = filepath.replace(/^app|\/app/, '');
  1195. }
  1196. fileInfo.filepath && (responseData.data = { filepath });
  1197. }
  1198. } catch (error) {
  1199. this.log(error);
  1200. this.setMessage(error.toString(), this.messageType.ERROR);
  1201. responseData.err = 1;
  1202. responseData.msg = error.toString();
  1203. }
  1204. }
  1205. ctx.body = responseData;
  1206. }
  1207. /**
  1208. * 删除变更令
  1209. * @param {Object} ctx - egg全局变量
  1210. * @return {void}
  1211. */
  1212. async delete(ctx) {
  1213. try {
  1214. const result = await ctx.service.change.delete(ctx.request.body.cid);
  1215. if (!result) {
  1216. throw '删除变更令失败';
  1217. }
  1218. ctx.redirect(ctx.request.header.referer);
  1219. } catch (err) {
  1220. console.log(err);
  1221. ctx.redirect(ctx.request.header.referer);
  1222. }
  1223. }
  1224. /**
  1225. * 变更令重新审批
  1226. * @param {Object} ctx - egg全局变量
  1227. * @return {void}
  1228. */
  1229. async checkAgain(ctx) {
  1230. try {
  1231. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1232. if (!changeData) {
  1233. throw '变更令数据错误';
  1234. }
  1235. // 获取终审
  1236. const auditInfo = (await this.ctx.service.changeAudit.getAllDataByCondition({ where: { cid: changeData.cid }, orders: [['usort', 'desc']], limit: 1, offset: 0 }))[0];
  1237. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== auditInfo.uid) {
  1238. throw '您无权进行该操作';
  1239. }
  1240. if (ctx.session.sessionUser.loginStatus === 0) {
  1241. const code = ctx.request.body.code;
  1242. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1243. if (!pa.auth_mobile) {
  1244. throw '未绑定手机号';
  1245. }
  1246. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1247. const cacheCode = await app.redis.get(cacheKey);
  1248. // console.log(cacheCode);
  1249. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1250. throw '验证码不正确!';
  1251. }
  1252. }
  1253. // 获取是否已存在调用变更令
  1254. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, changeData.cid);
  1255. const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  1256. if (stageChangeNum !== 0) {
  1257. throw '该变更令已被调用,无法重新审批';
  1258. }
  1259. // 重新审批
  1260. const result = await ctx.service.change.checkAgain(changeData.cid);
  1261. if (!result) {
  1262. throw '重新审批失败';
  1263. }
  1264. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1265. ctx.body = {
  1266. err: 0,
  1267. url: ctx.request.header.referer,
  1268. msg: '',
  1269. };
  1270. } catch (err) {
  1271. console.log(err);
  1272. // ctx.redirect(ctx.request.header.referer);
  1273. ctx.body = {
  1274. err: 1,
  1275. // url: ctx.request.header.referer,
  1276. msg: err,
  1277. };
  1278. }
  1279. }
  1280. /**
  1281. * 变更令修订重新上报
  1282. * @param {Object} ctx - egg全局变量
  1283. * @return {void}
  1284. */
  1285. async checkRevise(ctx) {
  1286. try {
  1287. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1288. if (!changeData) {
  1289. throw '变更令数据错误';
  1290. }
  1291. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== changeData.uid) {
  1292. throw '您无权进行该操作';
  1293. }
  1294. if (ctx.session.sessionUser.loginStatus === 0) {
  1295. const code = ctx.request.body.code;
  1296. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1297. if (!pa.auth_mobile) {
  1298. throw '未绑定手机号';
  1299. }
  1300. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1301. const cacheCode = await app.redis.get(cacheKey);
  1302. // console.log(cacheCode);
  1303. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1304. throw '验证码不正确!';
  1305. }
  1306. }
  1307. // 获取是否已存在调用变更令
  1308. // const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, changeData.cid);
  1309. // const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  1310. // if (stageChangeNum !== 0) {
  1311. // throw '该变更令已被调用,无法重新审批';
  1312. // }
  1313. // 重新审批
  1314. const result = await ctx.service.change.checkRevise(changeData.cid);
  1315. if (!result) {
  1316. throw '修订发起失败';
  1317. }
  1318. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1319. ctx.body = {
  1320. err: 0,
  1321. url: ctx.request.header.referer,
  1322. msg: '',
  1323. };
  1324. } catch (err) {
  1325. console.log(err);
  1326. // ctx.redirect(ctx.request.header.referer);
  1327. ctx.body = {
  1328. err: 1,
  1329. // url: ctx.request.header.referer,
  1330. msg: err,
  1331. };
  1332. }
  1333. }
  1334. /**
  1335. * 获取变更清单
  1336. * @param ctx
  1337. * @return {Promise<void>}
  1338. */
  1339. async bills(ctx) {
  1340. try {
  1341. const data = JSON.parse(ctx.request.body.data);
  1342. const responseData = { err: 0, msg: '', data: [] };
  1343. switch (data.type) {
  1344. case 'gather':
  1345. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  1346. break;
  1347. default:
  1348. throw '查询的数据不存在';
  1349. }
  1350. ctx.body = responseData;
  1351. } catch (err) {
  1352. this.log(err);
  1353. this.ajaxErrorBody(err, '获取变更清单失败');
  1354. }
  1355. }
  1356. /**
  1357. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  1358. * @param ctx
  1359. * @return {Promise<void>}
  1360. */
  1361. async checkCodeRepeat(ctx) {
  1362. const responseData = {
  1363. err: 0,
  1364. msg: '',
  1365. data: '',
  1366. };
  1367. try {
  1368. const tenderId = ctx.params.id;
  1369. const cid = ctx.params.cid;
  1370. const data = JSON.parse(ctx.request.body.data);
  1371. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  1372. if (result) {
  1373. throw '该变更令号(批复编号)已使用';
  1374. }
  1375. } catch (err) {
  1376. responseData.err = 1;
  1377. responseData.msg = err;
  1378. }
  1379. ctx.body = responseData;
  1380. }
  1381. /**
  1382. * 拷贝其他变更令
  1383. * @param {object} ctx - 全局上下文
  1384. */
  1385. async copyChange(ctx) {
  1386. const responseData = {
  1387. err: 0,
  1388. msg: '',
  1389. data: '',
  1390. };
  1391. try {
  1392. const cid = ctx.params.cid;
  1393. const copy_cid = JSON.parse(ctx.request.body.data);
  1394. const result = await ctx.service.change.handleCopyChange(cid, copy_cid);
  1395. if (!result) {
  1396. responseData.err = 1;
  1397. responseData.msg = '拷贝失败!';
  1398. }
  1399. } catch (error) {
  1400. responseData.err = 1;
  1401. responseData.msg = error;
  1402. }
  1403. ctx.body = responseData;
  1404. }
  1405. }
  1406. return ChangeController;
  1407. };