change_controller.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2018/8/14
  7. * @version
  8. */
  9. const moment = require('moment');
  10. const sendToWormhole = require('stream-wormhole');
  11. const fs = require('fs');
  12. const path = require('path');
  13. const audit = require('../const/audit');
  14. const codeRuleConst = require('../const/code_rule');
  15. const changeConst = require('../const/change');
  16. const accountGroup = require('../const/account_group').group;
  17. const shenpiConst = require('../const/shenpi');
  18. // const tenderMenu = require('../../config/menu').tenderMenu;
  19. module.exports = app => {
  20. class ChangeController extends app.BaseController {
  21. /**
  22. * 构造函数
  23. *
  24. * @param {Object} ctx - egg全局变量
  25. * @return {void}
  26. */
  27. constructor(ctx) {
  28. super(ctx);
  29. ctx.showProject = true;
  30. ctx.showTender = true;
  31. ctx.showTitle = true;
  32. }
  33. async _filterChanges(ctx, status = 0) {
  34. const tenderId = ctx.params.id;
  35. ctx.session.sessionUser.tenderId = tenderId;
  36. const tender = await this.service.tender.getDataById(tenderId);
  37. // const tenderList = await this.service.tender.getList();
  38. const page = ctx.page;
  39. const changes = await ctx.service.change.getListByStatus(tender.id, status);
  40. const total = await ctx.service.change.getCountByStatus(tender.id, status);
  41. if (changes !== null) {
  42. let i = 0;
  43. for (const c of changes) {
  44. const status = c.status === audit.flow.status.uncheck ? 0 : 1;
  45. // 根据审批人对当前变更令的状态取不同的展示方式。
  46. let changeAudit = '';
  47. let auditStatus = 0;
  48. switch (c.status) {
  49. case 1:
  50. auditStatus = 1;
  51. break;
  52. case 2:
  53. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  54. auditStatus = changeAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  55. break;
  56. case 3:
  57. case 4:
  58. auditStatus = 0;
  59. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  60. break;
  61. case 5:
  62. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times - 1, status);
  63. auditStatus = c.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  64. break;
  65. case 6:
  66. changeAudit = await ctx.service.changeAudit.getLastBackUser(c.cid, c.times);
  67. const checkingAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  68. auditStatus = checkingAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  69. break;
  70. default:
  71. break;
  72. }
  73. changes[i].changeAudit = changeAudit;
  74. changes[i].auditStatus = auditStatus;
  75. i++;
  76. }
  77. }
  78. // 分页相关
  79. const pageInfo = {
  80. page,
  81. total: Math.ceil(total / app.config.pageSize),
  82. queryData: JSON.stringify(ctx.urlInfo.query),
  83. };
  84. const filter = JSON.parse(JSON.stringify(audit.filter));
  85. filter.count = [];
  86. filter.count[filter.status.pending] = await ctx.service.change.getCountByStatus(tender.id, filter.status.pending);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  87. filter.count[filter.status.uncheck] = await ctx.service.change.getCountByStatus(tender.id, filter.status.uncheck);// await ctx.service.change.checkingDatas(tender.id, ctx.session.sessionUser.accountId);
  88. filter.count[filter.status.checking] = await ctx.service.change.getCountByStatus(tender.id, filter.status.checking);// await ctx.service.change.checkedDatas(tender.id, ctx.session.sessionUser.accountId);
  89. filter.count[filter.status.checked] = await ctx.service.change.getCountByStatus(tender.id, filter.status.checked);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  90. filter.count[filter.status.checkNo] = await ctx.service.change.getCountByStatus(tender.id, filter.status.checkNo);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  91. const codeRule = tender.c_rule ? JSON.parse(tender.c_rule) : [];
  92. for (const rule of codeRule) {
  93. switch (rule.rule_type) {
  94. case codeRuleConst.measure.ruleType.dealCode:
  95. rule.preview = ctx.tender.info.deal_info.dealCode;
  96. break;
  97. case codeRuleConst.measure.ruleType.tenderName:
  98. rule.preview = tender.name;
  99. break;
  100. case codeRuleConst.measure.ruleType.inDate:
  101. rule.preview = moment().format('YYYY');
  102. break;
  103. case codeRuleConst.measure.ruleType.text:
  104. rule.preview = rule.text;
  105. break;
  106. case codeRuleConst.measure.ruleType.addNo:
  107. const s = '0000000000';
  108. rule.preview = s.substr(s.length - rule.format);
  109. break;
  110. default: break;
  111. }
  112. }
  113. const renderData = {
  114. uid: ctx.session.sessionUser.accountId,
  115. moment,
  116. tender,
  117. // tenderList,
  118. pageInfo,
  119. changes,
  120. filter,
  121. status,
  122. codeRule,
  123. dealCode: ctx.tender.info.deal_info.dealCode,
  124. auditConst: audit.flow,
  125. changeConst,
  126. ruleType: codeRuleConst.ruleType.change,
  127. ruleConst: codeRuleConst.measure,
  128. tenderMenu: this.menu.tenderMenu,
  129. preUrl: '/tender/' + tenderId,
  130. tpUnit: ctx.tender.info.decimal.tp,
  131. };
  132. await this.layout('change/index.ejs', renderData, 'change/modal.ejs');
  133. }
  134. /**
  135. * 变更管理 页面 (Get)
  136. *
  137. * @param {Object} ctx - egg全局变量
  138. * @return {void}
  139. */
  140. async index(ctx) {
  141. try {
  142. await this._filterChanges(ctx);
  143. } catch (err) {
  144. this.log(err);
  145. ctx.redirect('/dashboard');
  146. }
  147. }
  148. /**
  149. *
  150. * @param {Object} ctx - egg全局变量
  151. * @return {void}
  152. */
  153. async newCode(ctx) {
  154. const responseData = {
  155. err: 0,
  156. msg: '',
  157. data: '',
  158. };
  159. try {
  160. const tenderId = ctx.params.id;
  161. if (!tenderId) {
  162. throw '当前未打开标段';
  163. }
  164. const tenderData = await ctx.service.tender.getDataById(tenderId);
  165. const cCodeRule = tenderData.c_rule !== null ? JSON.parse(tenderData.c_rule) : [];
  166. const code = [];
  167. for (const rule of cCodeRule) {
  168. switch (rule.rule_type) {
  169. case codeRuleConst.measure.ruleType.dealCode:
  170. code.push(ctx.tender.info.deal_info.dealCode);
  171. break;
  172. case codeRuleConst.measure.ruleType.tenderName:
  173. code.push(tenderData.name);
  174. break;
  175. case codeRuleConst.measure.ruleType.text:
  176. code.push(rule.text);
  177. break;
  178. case codeRuleConst.measure.ruleType.inDate:
  179. code.push(moment().format('YYYY'));
  180. break;
  181. case codeRuleConst.measure.ruleType.addNo:
  182. let s = '0000000000';
  183. const count = rule.start + await ctx.service.change.count({ tid: tenderId });
  184. s = s + count;
  185. code.push(s.substr(s.length - rule.format));
  186. break;
  187. default: break;
  188. }
  189. }
  190. responseData.data = code.join(tenderData.c_connector !== null && tenderData.c_connector !== 3 ? codeRuleConst.measure.connectorString[tenderData.c_connector] : '');
  191. } catch (err) {
  192. responseData.err = 1;
  193. responseData.msg = err;
  194. }
  195. ctx.body = responseData;
  196. }
  197. /**
  198. * 新增变更 (Post)
  199. *
  200. * @param {Object} ctx - egg全局变量
  201. * @return {void}
  202. */
  203. async add(ctx) {
  204. try {
  205. const tenderId = ctx.params.id;
  206. if (!tenderId) {
  207. throw '当前未打开标段';
  208. }
  209. const data = JSON.parse(ctx.request.body.data);
  210. if (!data.code || data.code === '' || !data.name || data.name === '') {
  211. throw '变更令号不能为空';
  212. }
  213. const change = await ctx.service.change.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  214. ctx.body = { err: 0, msg: '', data: change };
  215. } catch (err) {
  216. this.log(err);
  217. ctx.body = { err: 1, msg: err.toString() };
  218. }
  219. }
  220. /**
  221. * 变更管理 状态筛选 页面 (Get)
  222. * @param {Object} ctx - egg全局变量
  223. * @return {void}
  224. */
  225. async status(ctx) {
  226. try {
  227. const status = parseInt(ctx.params.status);
  228. await this._filterChanges(ctx, status);
  229. } catch (err) {
  230. this.logger.error(err);
  231. ctx.redirect('/tender/' + ctx.params.id + '/change');
  232. }
  233. }
  234. /**
  235. * 变更信息 页面 (Get)
  236. *
  237. * @param {Object} ctx - egg全局变量
  238. * @return {void}
  239. */
  240. async info(ctx) {
  241. try {
  242. const whiteList = this.ctx.app.config.multipart.whitelist;
  243. const tenderid = ctx.params.id !== undefined ? ctx.params.id : ctx.session.sessionUser.tenderId;
  244. ctx.session.sessionUser.tenderId = tenderid;
  245. const tender = await ctx.service.tender.getDataById(tenderid);
  246. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  247. // 后台判断当前人查看info状态
  248. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  249. // 获取附件列表
  250. const attList = await ctx.service.changeAtt.getChangeAttachment(ctx.params.cid);
  251. // 根据auditStatus获取审批人列表
  252. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  253. // 获取已选清单
  254. let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  255. // 获取用户人验证手机号
  256. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  257. const auth_mobile = pa.auth_mobile;
  258. const renderData = {
  259. uid: ctx.session.sessionUser.accountId,
  260. tender,
  261. change,
  262. changeConst,
  263. auditStatus,
  264. auditConst: audit.flow,
  265. ledgerConsts: audit.ledger.status,
  266. attList,
  267. whiteList,
  268. auditList,
  269. changeList,
  270. tpUnit: ctx.tender.info.decimal.tp,
  271. upUnit: ctx.tender.info.decimal.up,
  272. authMobile: auth_mobile,
  273. shenpiConst,
  274. };
  275. // 根据auditStatus状态获取的不同的数据
  276. if (auditStatus === 1 || auditStatus === 2) {
  277. renderData.changeUnits = changeConst.units;
  278. renderData.precision = ctx.tender.info.precision;
  279. // renderData.accountGroup = accountGroup;
  280. // 获取所有项目参与者
  281. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  282. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  283. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  284. });
  285. renderData.accountList = accountList;
  286. renderData.accountGroup = accountGroup.map((item, idx) => {
  287. const groupList = accountList.filter(item => item.account_group === idx);
  288. return { groupName: item, groupList };
  289. });
  290. // 重新上报获取审批流程
  291. if (auditStatus === 2) {
  292. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  293. // 展示页右侧审批流程列表
  294. const auditList3 = [];
  295. for (let time = 1; time <= change.times - 1; time++) {
  296. const auditTimeList = [];
  297. let max_sort = 1;
  298. for (const al of auditList2) {
  299. if (al.times === time) {
  300. auditTimeList.push(al);
  301. if (al.usite > max_sort) {
  302. max_sort = al.usite;
  303. }
  304. }
  305. }
  306. for (const i in auditTimeList) {
  307. auditTimeList[i].max_sort = max_sort;
  308. }
  309. auditList3.push(auditTimeList);
  310. }
  311. renderData.auditList3 = auditList3;
  312. }
  313. // 根据清单获取提交数据和计算总金额
  314. const changeListData = [];
  315. const changeWhiteListData = [];
  316. let ototalCost = 0;
  317. let ctotalCost = 0;
  318. for (const cl of changeList) {
  319. const cLArray = [
  320. cl.code,
  321. cl.name,
  322. cl.bwmx,
  323. cl.unit,
  324. cl.unit_price,
  325. cl.oamount,
  326. cl.camount,
  327. cl.detail,
  328. cl.lid,
  329. cl.xmj_code,
  330. cl.xmj_jldy,
  331. ];
  332. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, ctx.tender.info.decimal.tp);
  333. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, ctx.tender.info.decimal.tp);
  334. if (cl.lid !== '0') {
  335. changeListData.push(cLArray.join('*;*'));
  336. } else {
  337. changeWhiteListData.push(cLArray.join('*;*'));
  338. }
  339. }
  340. renderData.changeListData = changeListData.join('^_^');
  341. renderData.changeWhiteListData = changeWhiteListData.join('^_^');
  342. renderData.ototalCost = ototalCost;
  343. renderData.ctotalCost = ctotalCost;
  344. // 获取公司列表
  345. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: tenderid } });
  346. renderData.companyList = companyList;
  347. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7) {
  348. // 展示页左侧审批流程列表和清单审批列表数据
  349. const times = change.status === audit.flow.status.back ?
  350. change.times - 1 : change.times;
  351. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  352. // 展示页右侧审批流程列表
  353. const auditList3 = [];
  354. for (let time = 1; time <= times; time++) {
  355. const auditTimeList = [];
  356. let max_sort = 1;
  357. for (const al of auditList) {
  358. if (al.times === time) {
  359. auditTimeList.push(al);
  360. if (al.usite > max_sort) {
  361. max_sort = al.usite;
  362. }
  363. }
  364. }
  365. for (const i in auditTimeList) {
  366. auditTimeList[i].max_sort = max_sort;
  367. }
  368. auditList3.push(auditTimeList);
  369. }
  370. renderData.auditList3 = auditList3;
  371. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  372. renderData.changeList = changeList;
  373. let ototalCost = 0;
  374. let ctotalCost = 0;
  375. let stotalCost = 0;
  376. const auditTotalCost = [];
  377. for (const cl of changeList) {
  378. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  379. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  380. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  381. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  382. // stotalCost += cl.samount !== '' && cl.unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.samount), renderData.tpUnit)) : 0;
  383. stotalCost += cl.samount !== '' && cl.unit_price !== null ? ctx.helper.mul(cl.unit_price, cl.samount, renderData.tpUnit) : 0;
  384. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  385. auditTotalCost.push(audit_amount);
  386. }
  387. renderData.ototalCost = ototalCost;
  388. renderData.ctotalCost = ctotalCost;
  389. renderData.stotalCost = stotalCost;
  390. // 清单表页赋值
  391. for (const [index, au] of auditList2.entries()) {
  392. if (au.usite !== 0) {
  393. au.list_amount = [];
  394. au.totalCost = 0;
  395. for (const [auindex, at] of auditTotalCost.entries()) {
  396. au.list_amount.push(at[index - 1]);
  397. // 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;
  398. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  399. }
  400. }
  401. }
  402. renderData.auditList2 = auditList2;
  403. } else if (auditStatus === 6) {
  404. // 展示页左侧审批流程列表和清单审批列表数据
  405. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  406. renderData.auditList2 = auditList2;
  407. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  408. for (const i in auditList3) {
  409. auditList3[i].max_sort = auditList2.length - 1;
  410. }
  411. renderData.auditList3 = auditList3;
  412. // 展示页右侧审批流程列表
  413. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  414. const auditList4 = [];
  415. for (let time = 1; time <= change.times; time++) {
  416. const auditTimeList = [];
  417. let max_sort = 1;
  418. for (const al of auditList5) {
  419. if (al.times === time) {
  420. auditTimeList.push(al);
  421. if (al.usite > max_sort) {
  422. max_sort = al.usite;
  423. }
  424. }
  425. }
  426. for (const i in auditTimeList) {
  427. auditTimeList[i].max_sort = max_sort;
  428. }
  429. if (auditTimeList.length > 0) {
  430. auditList4.push(auditTimeList);
  431. }
  432. }
  433. renderData.auditList4 = auditList4;
  434. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  435. renderData.changeList = changeList;
  436. let ototalCost = 0;
  437. let ctotalCost = 0;
  438. const auditTotalCost = [];
  439. const auditUnit = [];
  440. for (const cl of changeList) {
  441. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  442. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  443. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  444. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  445. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  446. auditTotalCost.push(audit_amount);
  447. }
  448. renderData.ototalCost = ototalCost;
  449. renderData.ctotalCost = ctotalCost;
  450. // 清单表页赋值
  451. for (const [index, au] of auditList.entries()) {
  452. if (au.usite !== 0) {
  453. au.list_amount = [];
  454. au.totalCost = 0;
  455. if (au.uid === renderData.uid) {
  456. for (const [auindex, at] of auditTotalCost.entries()) {
  457. // if (at[index - 2] !== undefined) {
  458. // au.list_amount.push(at[index - 2]);
  459. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 2]), renderData.tpUnit));
  460. // } else if (at[index - 2] === undefined) {
  461. // au.list_amount.push(changeList[auindex].camount);
  462. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].camount), renderData.tpUnit));
  463. // }
  464. au.list_amount.push(changeList[auindex].spamount);
  465. // au.totalCost += changeList[auindex].unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].spamount), renderData.tpUnit));
  466. au.totalCost += changeList[auindex].unit_price === null ? 0 : ctx.helper.mul(changeList[auindex].unit_price, changeList[auindex].spamount, renderData.tpUnit);
  467. }
  468. } else {
  469. for (const [auindex, at] of auditTotalCost.entries()) {
  470. au.list_amount.push(at[index - 1]);
  471. // 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;
  472. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  473. }
  474. }
  475. }
  476. }
  477. }
  478. renderData.auditList = auditList;
  479. // 获取是否已存在调用变更令
  480. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  481. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  482. await this.layout('change/info.ejs', renderData, 'change/info_modal.ejs');
  483. } catch (err) {
  484. this.log(err);
  485. ctx.redirect('/tender/' + ctx.params.id + '/change');
  486. }
  487. }
  488. async defaultBills(ctx) {
  489. try {
  490. const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  491. const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  492. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  493. ctx.body = { err: 0, msg: '', data: { bills: ledgerData, pos: posData, dealBills } };
  494. } catch (err) {
  495. this.log(err);
  496. ctx.body = { err: 1, msg: err.toString(), data: [] };
  497. }
  498. }
  499. /**
  500. * 变更令上报和保存
  501. * @param {Object} ctx - egg全局变量
  502. * @return {void}
  503. */
  504. async save(ctx) {
  505. // 变更令信息
  506. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  507. try {
  508. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  509. if (!result) {
  510. throw '上报失败';
  511. }
  512. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  513. ctx.body = { err: 0, msg: '保存成功' };
  514. } else {
  515. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  516. }
  517. } catch (err) {
  518. this.log(err);
  519. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  520. ctx.body = { err: 1, msg: err.toString() };
  521. } else {
  522. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  523. }
  524. }
  525. }
  526. /**
  527. * 变更令审批
  528. * @param {Object} ctx - egg全局变量
  529. * @return {void}
  530. */
  531. async approval(ctx) {
  532. try {
  533. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.change_id });
  534. if (!changeData) {
  535. throw '变更令数据错误';
  536. }
  537. const status = parseInt(ctx.request.body.status);
  538. let result = false;
  539. const pid = this.ctx.session.sessionProject.id;
  540. switch (status) {
  541. case 3:// 审批通过
  542. result = await ctx.service.change.approvalSuccess(pid, ctx.request.body, changeData);
  543. break;
  544. case 4:// 审批终止
  545. result = await ctx.service.change.approvalStop(ctx.request.body);
  546. break;
  547. case 5:// 审批退回到原报人
  548. result = await ctx.service.change.approvalBack(pid, ctx.request.body, changeData);
  549. break;
  550. case 6:// 审批退回到上一个审批人
  551. result = await ctx.service.change.approvalBackNew(pid, ctx.request.body, changeData);
  552. break;
  553. default:break;
  554. }
  555. if (!result) {
  556. throw '审批失败';
  557. }
  558. ctx.redirect(ctx.request.header.referer);
  559. } catch (err) {
  560. console.log(err);
  561. ctx.redirect(ctx.request.header.referer);
  562. }
  563. }
  564. /**
  565. * 变更公司管理
  566. * @param {Object} ctx - egg全局变量
  567. * @return {void}
  568. */
  569. async updateCompany(ctx) {
  570. const responseData = {
  571. err: 0,
  572. msg: '',
  573. data: '',
  574. };
  575. try {
  576. const data = JSON.parse(ctx.request.body.data);
  577. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  578. throw '参数有误';
  579. }
  580. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  581. responseData.data = { add: addCompany, select: selectCompany };
  582. } catch (err) {
  583. responseData.err = 1;
  584. responseData.msg = err;
  585. }
  586. ctx.body = responseData;
  587. }
  588. /**
  589. * 上传附件
  590. * @param {Object} ctx - egg全局变量
  591. * @return {void}
  592. */
  593. async uploadFile(ctx) {
  594. const responseData = {
  595. err: 0,
  596. msg: '',
  597. data: [],
  598. };
  599. let stream;
  600. try {
  601. const parts = ctx.multipart({ autoFields: true });
  602. const files = [];
  603. let index = 0;
  604. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  605. const extra_upload = change.status === audit.flow.status.checked;
  606. while ((stream = await parts()) !== undefined) {
  607. // 判断用户是否选择上传文件
  608. if (!stream.filename) {
  609. throw '请选择上传的文件!';
  610. }
  611. // const create_time = Date.parse(new Date()) / 1000;
  612. // const fileInfo = path.parse(stream.filename);
  613. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  614. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  615. // // 判断文件夹是否存在,不存在则直接创建文件夹
  616. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  617. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  618. // }
  619. // // 保存文件
  620. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  621. const fileInfo = path.parse(stream.filename);
  622. const create_time = Date.parse(new Date()) / 1000;
  623. const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  624. await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  625. await sendToWormhole(stream);
  626. // 保存数据到att表
  627. const fileData = {
  628. in_time: create_time,
  629. filename: fileInfo.name,
  630. fileext: fileInfo.ext,
  631. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  632. filepath,
  633. extra_upload,
  634. };
  635. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  636. if (!result) {
  637. throw '导入数据库保存失败';
  638. }
  639. fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  640. fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  641. fileData.id = result.insertId;
  642. delete fileData.filepath;
  643. files.push(fileData);
  644. ++index;
  645. }
  646. responseData.data = files;
  647. } catch (err) {
  648. this.log(err);
  649. // 失败需要消耗掉stream 以防卡死
  650. if (stream) {
  651. await sendToWormhole(stream);
  652. }
  653. this.setMessage(err.toString(), this.messageType.ERROR);
  654. }
  655. ctx.body = responseData;
  656. }
  657. /**
  658. * 下载附件
  659. * @param {Object} ctx - egg全局变量
  660. * @return {void}
  661. */
  662. async downloadFile(ctx) {
  663. const id = ctx.params.id;
  664. if (id) {
  665. try {
  666. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  667. if (fileInfo !== undefined && fileInfo !== '') {
  668. const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  669. // 解决中文无法下载问题
  670. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  671. let disposition = '';
  672. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  673. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  674. } else if (userAgent.indexOf('firefox') >= 0) {
  675. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  676. } else {
  677. /* safari等其他非主流浏览器只能自求多福了 */
  678. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  679. }
  680. ctx.response.set({
  681. 'Content-Type': 'application/octet-stream',
  682. 'Content-Disposition': disposition,
  683. 'Content-Length': fileInfo.filesize,
  684. });
  685. ctx.body = await fs.createReadStream(fileName);
  686. } else {
  687. throw '不存在该文件';
  688. }
  689. } catch (err) {
  690. this.log(err);
  691. this.setMessage(err.toString(), this.messageType.ERROR);
  692. }
  693. }
  694. }
  695. /**
  696. * 批量下载 - 压缩成zip文件返回
  697. * @param {Oject} ctx - 全局上下文
  698. */
  699. async downloadZip(ctx) {
  700. try {
  701. const fileIds = JSON.parse(ctx.request.query.fileIds);
  702. // const { fileIds } = JSON.parse(ctx.request.body.data);
  703. // console.log('fileIds', fileIds);
  704. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  705. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  706. const time = Date.now();
  707. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  708. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  709. // 解决中文无法下载问题
  710. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  711. let disposition = '';
  712. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  713. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  714. } else if (userAgent.indexOf('firefox') >= 0) {
  715. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  716. } else {
  717. /* safari等其他非主流浏览器只能自求多福了 */
  718. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  719. }
  720. ctx.response.set({
  721. 'Content-Type': 'application/octet-stream',
  722. 'Content-Disposition': disposition,
  723. 'Content-Length': size,
  724. });
  725. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  726. ctx.body = readStream;
  727. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  728. readStream.on('close', () => {
  729. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  730. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  731. }
  732. });
  733. } catch (error) {
  734. this.log(error);
  735. }
  736. }
  737. /**
  738. * 删除附件
  739. * @param {Object} ctx - egg全局变量
  740. * @return {void}
  741. */
  742. async deleteFile(ctx) {
  743. const responseData = {
  744. err: 0,
  745. msg: '',
  746. data: '',
  747. };
  748. try {
  749. const data = JSON.parse(ctx.request.body.data);
  750. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  751. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  752. if (!fileInfo || !Object.keys(fileInfo).length) {
  753. throw '该文件不存在';
  754. }
  755. if (!fileInfo.extra_upload && change.status === audit.flow.status.checked) {
  756. throw '无权限删除';
  757. }
  758. if (fileInfo !== undefined && fileInfo !== '') {
  759. // 先删除文件
  760. await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  761. // 再删除数据库
  762. await ctx.service.changeAtt.deleteById(data.id);
  763. responseData.data = '';
  764. } else {
  765. throw '不存在该文件';
  766. }
  767. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  768. // throw '参数有误';
  769. // }
  770. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  771. // responseData.data = { add: addCompany, select: selectCompany };
  772. } catch (err) {
  773. responseData.err = 1;
  774. responseData.msg = err;
  775. }
  776. ctx.body = responseData;
  777. }
  778. /**
  779. * 查看附件
  780. * @param {Object} ctx - egg全局变量
  781. * @return {void}
  782. */
  783. async checkFile(ctx) {
  784. const responseData = { err: 0, msg: '' };
  785. const id = parseInt(ctx.params.id);
  786. if (id) {
  787. try {
  788. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  789. if (fileInfo && Object.keys(fileInfo).length) {
  790. let filepath = fileInfo.filepath;
  791. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  792. filepath = `/change/download/file/${fileInfo.id}`;
  793. } else {
  794. filepath = filepath.replace(/^app|\/app/, '');
  795. }
  796. fileInfo.filepath && (responseData.data = { filepath });
  797. }
  798. } catch (error) {
  799. this.log(error);
  800. this.setMessage(error.toString(), this.messageType.ERROR);
  801. responseData.err = 1;
  802. responseData.msg = error.toString();
  803. }
  804. }
  805. ctx.body = responseData;
  806. }
  807. /**
  808. * 删除变更令
  809. * @param {Object} ctx - egg全局变量
  810. * @return {void}
  811. */
  812. async delete(ctx) {
  813. try {
  814. const result = await ctx.service.change.delete(ctx.request.body.cid);
  815. if (!result) {
  816. throw '删除变更令失败';
  817. }
  818. ctx.redirect(ctx.request.header.referer);
  819. } catch (err) {
  820. console.log(err);
  821. ctx.redirect(ctx.request.header.referer);
  822. }
  823. }
  824. /**
  825. * 变更令重新审批
  826. * @param {Object} ctx - egg全局变量
  827. * @return {void}
  828. */
  829. async checkAgain(ctx) {
  830. try {
  831. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  832. if (!changeData) {
  833. throw '变更令数据错误';
  834. }
  835. // 获取终审
  836. const auditInfo = (await this.ctx.service.changeAudit.getAllDataByCondition({ where: { cid: changeData.cid }, orders: [['usort', 'desc']], limit: 1, offset: 0 }))[0];
  837. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== auditInfo.uid) {
  838. throw '您无权进行该操作';
  839. }
  840. if (ctx.session.sessionUser.loginStatus === 0) {
  841. const code = ctx.request.body.code;
  842. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  843. if (!pa.auth_mobile) {
  844. throw '未绑定手机号';
  845. }
  846. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  847. const cacheCode = await app.redis.get(cacheKey);
  848. // console.log(cacheCode);
  849. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  850. throw '验证码不正确!';
  851. }
  852. }
  853. // 重新审批
  854. const result = await ctx.service.change.checkAgain(changeData.cid);
  855. if (!result) {
  856. throw '重新审批失败';
  857. }
  858. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  859. ctx.body = {
  860. err: 0,
  861. url: ctx.request.header.referer,
  862. msg: '',
  863. };
  864. } catch (err) {
  865. console.log(err);
  866. // ctx.redirect(ctx.request.header.referer);
  867. ctx.body = {
  868. err: 1,
  869. // url: ctx.request.header.referer,
  870. msg: err,
  871. };
  872. }
  873. }
  874. /**
  875. * 获取变更清单
  876. * @param ctx
  877. * @return {Promise<void>}
  878. */
  879. async bills(ctx) {
  880. try {
  881. const data = JSON.parse(ctx.request.body.data);
  882. const responseData = { err: 0, msg: '', data: [] };
  883. switch (data.type) {
  884. case 'gather':
  885. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  886. break;
  887. default:
  888. throw '查询的数据不存在';
  889. }
  890. ctx.body = responseData;
  891. } catch (err) {
  892. this.log(err);
  893. this.ajaxErrorBody(err, '获取变更清单失败');
  894. }
  895. }
  896. /**
  897. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  898. * @param ctx
  899. * @return {Promise<void>}
  900. */
  901. async checkCodeRepeat(ctx) {
  902. const responseData = {
  903. err: 0,
  904. msg: '',
  905. data: '',
  906. };
  907. try {
  908. const tenderId = ctx.params.id;
  909. const cid = ctx.params.cid;
  910. const data = JSON.parse(ctx.request.body.data);
  911. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  912. if (result) {
  913. throw '该变更令号(批复编号)已使用';
  914. }
  915. } catch (err) {
  916. responseData.err = 1;
  917. responseData.msg = err;
  918. }
  919. ctx.body = responseData;
  920. }
  921. }
  922. return ChangeController;
  923. };