change_controller.js 45 KB

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