change_controller.js 70 KB

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