change_controller.js 69 KB

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