change_controller.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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; 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 auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  350. // 展示页右侧审批流程列表
  351. const auditList3 = [];
  352. for (let time = 1; time <= change.times; time++) {
  353. const auditTimeList = [];
  354. let max_sort = 1;
  355. for (const al of auditList) {
  356. if (al.times === time) {
  357. auditTimeList.push(al);
  358. if (al.usite > max_sort) {
  359. max_sort = al.usite;
  360. }
  361. }
  362. }
  363. for (const i in auditTimeList) {
  364. auditTimeList[i].max_sort = max_sort;
  365. }
  366. auditList3.push(auditTimeList);
  367. }
  368. renderData.auditList3 = auditList3;
  369. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  370. renderData.changeList = changeList;
  371. let ototalCost = 0;
  372. let ctotalCost = 0;
  373. let stotalCost = 0;
  374. const auditTotalCost = [];
  375. for (const cl of changeList) {
  376. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  377. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  378. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  379. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  380. // stotalCost += cl.samount !== '' && cl.unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.samount), renderData.tpUnit)) : 0;
  381. stotalCost += cl.samount !== '' && cl.unit_price !== null ? ctx.helper.mul(cl.unit_price, cl.samount, renderData.tpUnit) : 0;
  382. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  383. auditTotalCost.push(audit_amount);
  384. }
  385. renderData.ototalCost = ototalCost;
  386. renderData.ctotalCost = ctotalCost;
  387. renderData.stotalCost = stotalCost;
  388. // 清单表页赋值
  389. for (const [index, au] of auditList2.entries()) {
  390. if (au.usite !== 0) {
  391. au.list_amount = [];
  392. au.totalCost = 0;
  393. for (const [auindex, at] of auditTotalCost.entries()) {
  394. au.list_amount.push(at[index - 1]);
  395. // 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;
  396. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  397. }
  398. }
  399. }
  400. renderData.auditList2 = auditList2;
  401. } else if (auditStatus === 6) {
  402. // 展示页左侧审批流程列表和清单审批列表数据
  403. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  404. renderData.auditList2 = auditList2;
  405. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  406. for (const i in auditList3) {
  407. auditList3[i].max_sort = auditList2.length - 1;
  408. }
  409. renderData.auditList3 = auditList3;
  410. // 展示页右侧审批流程列表
  411. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  412. const auditList4 = [];
  413. for (let time = 1; time <= change.times; time++) {
  414. const auditTimeList = [];
  415. let max_sort = 1;
  416. for (const al of auditList5) {
  417. if (al.times === time) {
  418. auditTimeList.push(al);
  419. if (al.usite > max_sort) {
  420. max_sort = al.usite;
  421. }
  422. }
  423. }
  424. for (const i in auditTimeList) {
  425. auditTimeList[i].max_sort = max_sort;
  426. }
  427. if (auditTimeList.length > 0) {
  428. auditList4.push(auditTimeList);
  429. }
  430. }
  431. renderData.auditList4 = auditList4;
  432. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  433. renderData.changeList = changeList;
  434. let ototalCost = 0;
  435. let ctotalCost = 0;
  436. const auditTotalCost = [];
  437. const auditUnit = [];
  438. for (const cl of changeList) {
  439. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  440. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  441. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  442. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  443. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  444. auditTotalCost.push(audit_amount);
  445. }
  446. renderData.ototalCost = ototalCost;
  447. renderData.ctotalCost = ctotalCost;
  448. // 清单表页赋值
  449. for (const [index, au] of auditList.entries()) {
  450. if (au.usite !== 0) {
  451. au.list_amount = [];
  452. au.totalCost = 0;
  453. if (au.uid === renderData.uid) {
  454. for (const [auindex, at] of auditTotalCost.entries()) {
  455. // if (at[index - 2] !== undefined) {
  456. // au.list_amount.push(at[index - 2]);
  457. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 2]), renderData.tpUnit));
  458. // } else if (at[index - 2] === undefined) {
  459. // au.list_amount.push(changeList[auindex].camount);
  460. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].camount), renderData.tpUnit));
  461. // }
  462. au.list_amount.push(changeList[auindex].spamount);
  463. // au.totalCost += changeList[auindex].unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].spamount), renderData.tpUnit));
  464. au.totalCost += changeList[auindex].unit_price === null ? 0 : ctx.helper.mul(changeList[auindex].unit_price, changeList[auindex].spamount, renderData.tpUnit);
  465. }
  466. } else {
  467. for (const [auindex, at] of auditTotalCost.entries()) {
  468. au.list_amount.push(at[index - 1]);
  469. // 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;
  470. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  471. }
  472. }
  473. }
  474. }
  475. }
  476. renderData.auditList = auditList;
  477. // 获取是否已存在调用变更令
  478. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  479. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  480. await this.layout('change/info.ejs', renderData, 'change/info_modal.ejs');
  481. } catch (err) {
  482. this.log(err);
  483. ctx.redirect('/tender/' + ctx.params.id + '/change');
  484. }
  485. }
  486. async defaultBills(ctx) {
  487. try {
  488. const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  489. const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  490. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  491. ctx.body = { err: 0, msg: '', data: { bills: ledgerData, pos: posData, dealBills } };
  492. } catch (err) {
  493. this.log(err);
  494. ctx.body = { err: 1, msg: err.toString(), data: [] };
  495. }
  496. }
  497. /**
  498. * 变更令上报和保存
  499. * @param {Object} ctx - egg全局变量
  500. * @return {void}
  501. */
  502. async save(ctx) {
  503. // 变更令信息
  504. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  505. try {
  506. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  507. if (!result) {
  508. throw '上报失败';
  509. }
  510. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  511. ctx.body = { err: 0, msg: '保存成功' };
  512. } else {
  513. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  514. }
  515. } catch (err) {
  516. this.log(err);
  517. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  518. ctx.body = { err: 1, msg: err.toString() };
  519. } else {
  520. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  521. }
  522. }
  523. }
  524. /**
  525. * 变更令审批
  526. * @param {Object} ctx - egg全局变量
  527. * @return {void}
  528. */
  529. async approval(ctx) {
  530. try {
  531. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.change_id });
  532. if (!changeData) {
  533. throw '变更令数据错误';
  534. }
  535. const status = parseInt(ctx.request.body.status);
  536. let result = false;
  537. const pid = this.ctx.session.sessionProject.id;
  538. switch (status) {
  539. case 3:// 审批通过
  540. result = await ctx.service.change.approvalSuccess(pid, ctx.request.body, changeData);
  541. break;
  542. case 4:// 审批终止
  543. result = await ctx.service.change.approvalStop(ctx.request.body);
  544. break;
  545. case 5:// 审批退回到原报人
  546. result = await ctx.service.change.approvalBack(pid, ctx.request.body, changeData);
  547. break;
  548. case 6:// 审批退回到上一个审批人
  549. result = await ctx.service.change.approvalBackNew(pid, ctx.request.body, changeData);
  550. break;
  551. default:break;
  552. }
  553. if (!result) {
  554. throw '审批失败';
  555. }
  556. ctx.redirect(ctx.request.header.referer);
  557. } catch (err) {
  558. console.log(err);
  559. ctx.redirect(ctx.request.header.referer);
  560. }
  561. }
  562. /**
  563. * 变更公司管理
  564. * @param {Object} ctx - egg全局变量
  565. * @return {void}
  566. */
  567. async updateCompany(ctx) {
  568. const responseData = {
  569. err: 0,
  570. msg: '',
  571. data: '',
  572. };
  573. try {
  574. const data = JSON.parse(ctx.request.body.data);
  575. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  576. throw '参数有误';
  577. }
  578. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  579. responseData.data = { add: addCompany, select: selectCompany };
  580. } catch (err) {
  581. responseData.err = 1;
  582. responseData.msg = err;
  583. }
  584. ctx.body = responseData;
  585. }
  586. /**
  587. * 上传附件
  588. * @param {Object} ctx - egg全局变量
  589. * @return {void}
  590. */
  591. async uploadFile(ctx) {
  592. const responseData = {
  593. err: 0,
  594. msg: '',
  595. data: [],
  596. };
  597. let stream;
  598. try {
  599. const parts = ctx.multipart({ autoFields: true });
  600. const files = [];
  601. let index = 0;
  602. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  603. const extra_upload = change.status === audit.flow.status.checked;
  604. while ((stream = await parts()) !== undefined) {
  605. // 判断用户是否选择上传文件
  606. if (!stream.filename) {
  607. throw '请选择上传的文件!';
  608. }
  609. // const create_time = Date.parse(new Date()) / 1000;
  610. // const fileInfo = path.parse(stream.filename);
  611. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  612. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  613. // // 判断文件夹是否存在,不存在则直接创建文件夹
  614. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  615. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  616. // }
  617. // // 保存文件
  618. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  619. const fileInfo = path.parse(stream.filename);
  620. const create_time = Date.parse(new Date()) / 1000;
  621. const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  622. await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  623. await sendToWormhole(stream);
  624. // 保存数据到att表
  625. const fileData = {
  626. in_time: create_time,
  627. filename: fileInfo.name,
  628. fileext: fileInfo.ext,
  629. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  630. filepath,
  631. extra_upload,
  632. };
  633. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  634. if (!result) {
  635. throw '导入数据库保存失败';
  636. }
  637. fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  638. fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  639. fileData.id = result.insertId;
  640. delete fileData.filepath;
  641. files.push(fileData);
  642. ++index;
  643. }
  644. responseData.data = files;
  645. } catch (err) {
  646. this.log(err);
  647. // 失败需要消耗掉stream 以防卡死
  648. if (stream) {
  649. await sendToWormhole(stream);
  650. }
  651. this.setMessage(err.toString(), this.messageType.ERROR);
  652. }
  653. ctx.body = responseData;
  654. }
  655. /**
  656. * 下载附件
  657. * @param {Object} ctx - egg全局变量
  658. * @return {void}
  659. */
  660. async downloadFile(ctx) {
  661. const id = ctx.params.id;
  662. if (id) {
  663. try {
  664. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  665. if (fileInfo !== undefined && fileInfo !== '') {
  666. const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  667. // 解决中文无法下载问题
  668. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  669. let disposition = '';
  670. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  671. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  672. } else if (userAgent.indexOf('firefox') >= 0) {
  673. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  674. } else {
  675. /* safari等其他非主流浏览器只能自求多福了 */
  676. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  677. }
  678. ctx.response.set({
  679. 'Content-Type': 'application/octet-stream',
  680. 'Content-Disposition': disposition,
  681. 'Content-Length': fileInfo.filesize,
  682. });
  683. ctx.body = await fs.createReadStream(fileName);
  684. } else {
  685. throw '不存在该文件';
  686. }
  687. } catch (err) {
  688. this.log(err);
  689. this.setMessage(err.toString(), this.messageType.ERROR);
  690. }
  691. }
  692. }
  693. /**
  694. * 批量下载 - 压缩成zip文件返回
  695. * @param {Oject} ctx - 全局上下文
  696. */
  697. async downloadZip(ctx) {
  698. try {
  699. const fileIds = JSON.parse(ctx.request.query.fileIds);
  700. // const { fileIds } = JSON.parse(ctx.request.body.data);
  701. // console.log('fileIds', fileIds);
  702. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  703. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  704. const time = Date.now();
  705. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  706. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  707. // 解决中文无法下载问题
  708. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  709. let disposition = '';
  710. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  711. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  712. } else if (userAgent.indexOf('firefox') >= 0) {
  713. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  714. } else {
  715. /* safari等其他非主流浏览器只能自求多福了 */
  716. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  717. }
  718. ctx.response.set({
  719. 'Content-Type': 'application/octet-stream',
  720. 'Content-Disposition': disposition,
  721. 'Content-Length': size,
  722. });
  723. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  724. ctx.body = readStream;
  725. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  726. readStream.on('close', () => {
  727. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  728. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  729. }
  730. });
  731. } catch (error) {
  732. this.log(error);
  733. }
  734. }
  735. /**
  736. * 删除附件
  737. * @param {Object} ctx - egg全局变量
  738. * @return {void}
  739. */
  740. async deleteFile(ctx) {
  741. const responseData = {
  742. err: 0,
  743. msg: '',
  744. data: '',
  745. };
  746. try {
  747. const data = JSON.parse(ctx.request.body.data);
  748. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  749. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  750. if (!fileInfo.extra_upload && change.status === audit.flow.status.checked) {
  751. throw '无权限删除';
  752. }
  753. if (fileInfo !== undefined && fileInfo !== '') {
  754. // 先删除文件
  755. await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  756. // 再删除数据库
  757. await ctx.service.changeAtt.deleteById(data.id);
  758. responseData.data = '';
  759. } else {
  760. throw '不存在该文件';
  761. }
  762. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  763. // throw '参数有误';
  764. // }
  765. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  766. // responseData.data = { add: addCompany, select: selectCompany };
  767. } catch (err) {
  768. responseData.err = 1;
  769. responseData.msg = err;
  770. }
  771. ctx.body = responseData;
  772. }
  773. /**
  774. * 查看附件
  775. * @param {Object} ctx - egg全局变量
  776. * @return {void}
  777. */
  778. async checkFile(ctx) {
  779. const responseData = { err: 0, msg: '' };
  780. const id = parseInt(ctx.params.id);
  781. if (id) {
  782. try {
  783. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  784. if (fileInfo && Object.keys(fileInfo).length) {
  785. let filepath = fileInfo.filepath;
  786. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  787. filepath = `/change/download/file/${fileInfo.id}`;
  788. } else {
  789. filepath = filepath.replace(/^app|\/app/, '');
  790. }
  791. fileInfo.filepath && (responseData.data = { filepath });
  792. }
  793. } catch (error) {
  794. this.log(error);
  795. this.setMessage(error.toString(), this.messageType.ERROR);
  796. responseData.err = 1;
  797. responseData.msg = error.toString();
  798. }
  799. }
  800. ctx.body = responseData;
  801. }
  802. /**
  803. * 删除变更令
  804. * @param {Object} ctx - egg全局变量
  805. * @return {void}
  806. */
  807. async delete(ctx) {
  808. try {
  809. const result = await ctx.service.change.delete(ctx.request.body.cid);
  810. if (!result) {
  811. throw '删除变更令失败';
  812. }
  813. ctx.redirect(ctx.request.header.referer);
  814. } catch (err) {
  815. console.log(err);
  816. ctx.redirect(ctx.request.header.referer);
  817. }
  818. }
  819. /**
  820. * 变更令重新审批
  821. * @param {Object} ctx - egg全局变量
  822. * @return {void}
  823. */
  824. async checkAgain(ctx) {
  825. try {
  826. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  827. if (!changeData) {
  828. throw '变更令数据错误';
  829. }
  830. // 获取终审
  831. const auditInfo = (await this.ctx.service.changeAudit.getAllDataByCondition({ where: { cid: changeData.cid }, orders: [['usort', 'desc']], limit: 1, offset: 0 }))[0];
  832. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== auditInfo.uid) {
  833. throw '您无权进行该操作';
  834. }
  835. if (ctx.session.sessionUser.loginStatus === 0) {
  836. const code = ctx.request.body.code;
  837. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  838. if (!pa.auth_mobile) {
  839. throw '未绑定手机号';
  840. }
  841. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  842. const cacheCode = await app.redis.get(cacheKey);
  843. // console.log(cacheCode);
  844. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  845. throw '验证码不正确!';
  846. }
  847. }
  848. // 重新审批
  849. const result = await ctx.service.change.checkAgain(changeData.cid);
  850. if (!result) {
  851. throw '重新审批失败';
  852. }
  853. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  854. ctx.body = {
  855. err: 0,
  856. url: ctx.request.header.referer,
  857. msg: '',
  858. };
  859. } catch (err) {
  860. console.log(err);
  861. // ctx.redirect(ctx.request.header.referer);
  862. ctx.body = {
  863. err: 1,
  864. // url: ctx.request.header.referer,
  865. msg: err,
  866. };
  867. }
  868. }
  869. /**
  870. * 获取变更清单
  871. * @param ctx
  872. * @return {Promise<void>}
  873. */
  874. async bills(ctx) {
  875. try {
  876. const data = JSON.parse(ctx.request.body.data);
  877. const responseData = { err: 0, msg: '', data: [] };
  878. switch (data.type) {
  879. case 'gather':
  880. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  881. break;
  882. default:
  883. throw '查询的数据不存在';
  884. }
  885. ctx.body = responseData;
  886. } catch (err) {
  887. this.log(err);
  888. this.ajaxErrorBody(err, '获取变更清单失败');
  889. }
  890. }
  891. /**
  892. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  893. * @param ctx
  894. * @return {Promise<void>}
  895. */
  896. async checkCodeRepeat(ctx) {
  897. const responseData = {
  898. err: 0,
  899. msg: '',
  900. data: '',
  901. };
  902. try {
  903. const tenderId = ctx.params.id;
  904. const cid = ctx.params.cid;
  905. const data = JSON.parse(ctx.request.body.data);
  906. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  907. if (result) {
  908. throw '该变更令号(批复编号)已使用';
  909. }
  910. } catch (err) {
  911. responseData.err = 1;
  912. responseData.msg = err;
  913. }
  914. ctx.body = responseData;
  915. }
  916. }
  917. return ChangeController;
  918. };