change_controller.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  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. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  597. const extra_upload = change.status === audit.flow.status.checked;
  598. while ((stream = await parts()) !== undefined) {
  599. // 判断用户是否选择上传文件
  600. if (!stream.filename) {
  601. throw '请选择上传的文件!';
  602. }
  603. // const create_time = Date.parse(new Date()) / 1000;
  604. // const fileInfo = path.parse(stream.filename);
  605. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  606. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  607. // // 判断文件夹是否存在,不存在则直接创建文件夹
  608. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  609. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  610. // }
  611. // // 保存文件
  612. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  613. const fileInfo = path.parse(stream.filename);
  614. const create_time = Date.parse(new Date()) / 1000;
  615. const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  616. await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  617. await sendToWormhole(stream);
  618. // 保存数据到att表
  619. const fileData = {
  620. in_time: create_time,
  621. filename: fileInfo.name,
  622. fileext: fileInfo.ext,
  623. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  624. filepath,
  625. extra_upload,
  626. };
  627. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  628. if (!result) {
  629. throw '导入数据库保存失败';
  630. }
  631. fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  632. fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  633. fileData.id = result.insertId;
  634. delete fileData.filepath;
  635. files.push(fileData);
  636. ++index;
  637. }
  638. responseData.data = files;
  639. } catch (err) {
  640. this.log(err);
  641. // 失败需要消耗掉stream 以防卡死
  642. if (stream) {
  643. await sendToWormhole(stream);
  644. }
  645. this.setMessage(err.toString(), this.messageType.ERROR);
  646. }
  647. ctx.body = responseData;
  648. }
  649. /**
  650. * 下载附件
  651. * @param {Object} ctx - egg全局变量
  652. * @return {void}
  653. */
  654. async downloadFile(ctx) {
  655. const id = ctx.params.id;
  656. if (id) {
  657. try {
  658. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  659. if (fileInfo !== undefined && fileInfo !== '') {
  660. const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  661. // 解决中文无法下载问题
  662. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  663. let disposition = '';
  664. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  665. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  666. } else if (userAgent.indexOf('firefox') >= 0) {
  667. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  668. } else {
  669. /* safari等其他非主流浏览器只能自求多福了 */
  670. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  671. }
  672. ctx.response.set({
  673. 'Content-Type': 'application/octet-stream',
  674. 'Content-Disposition': disposition,
  675. 'Content-Length': fileInfo.filesize,
  676. });
  677. ctx.body = await fs.createReadStream(fileName);
  678. } else {
  679. throw '不存在该文件';
  680. }
  681. } catch (err) {
  682. this.log(err);
  683. this.setMessage(err.toString(), this.messageType.ERROR);
  684. }
  685. }
  686. }
  687. /**
  688. * 批量下载 - 压缩成zip文件返回
  689. * @param {Oject} ctx - 全局上下文
  690. */
  691. async downloadZip(ctx) {
  692. try {
  693. const fileIds = JSON.parse(ctx.request.query.fileIds);
  694. // const { fileIds } = JSON.parse(ctx.request.body.data);
  695. // console.log('fileIds', fileIds);
  696. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  697. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  698. const time = Date.now();
  699. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  700. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  701. // 解决中文无法下载问题
  702. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  703. let disposition = '';
  704. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  705. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  706. } else if (userAgent.indexOf('firefox') >= 0) {
  707. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  708. } else {
  709. /* safari等其他非主流浏览器只能自求多福了 */
  710. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  711. }
  712. ctx.response.set({
  713. 'Content-Type': 'application/octet-stream',
  714. 'Content-Disposition': disposition,
  715. 'Content-Length': size,
  716. });
  717. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  718. ctx.body = readStream;
  719. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  720. readStream.on('close', () => {
  721. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  722. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  723. }
  724. });
  725. } catch (error) {
  726. this.log(error);
  727. }
  728. }
  729. /**
  730. * 删除附件
  731. * @param {Object} ctx - egg全局变量
  732. * @return {void}
  733. */
  734. async deleteFile(ctx) {
  735. const responseData = {
  736. err: 0,
  737. msg: '',
  738. data: '',
  739. };
  740. try {
  741. const data = JSON.parse(ctx.request.body.data);
  742. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  743. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  744. if (!fileInfo.extra_upload && change.status === audit.flow.status.checked) {
  745. throw '无权限删除';
  746. }
  747. if (fileInfo !== undefined && fileInfo !== '') {
  748. // 先删除文件
  749. await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  750. // 再删除数据库
  751. await ctx.service.changeAtt.deleteById(data.id);
  752. responseData.data = '';
  753. } else {
  754. throw '不存在该文件';
  755. }
  756. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  757. // throw '参数有误';
  758. // }
  759. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  760. // responseData.data = { add: addCompany, select: selectCompany };
  761. } catch (err) {
  762. responseData.err = 1;
  763. responseData.msg = err;
  764. }
  765. ctx.body = responseData;
  766. }
  767. /**
  768. * 查看附件
  769. * @param {Object} ctx - egg全局变量
  770. * @return {void}
  771. */
  772. async checkFile(ctx) {
  773. const responseData = { err: 0, msg: '' };
  774. const id = parseInt(ctx.params.id);
  775. if (id) {
  776. try {
  777. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  778. if (fileInfo && Object.keys(fileInfo).length) {
  779. let filepath = fileInfo.filepath;
  780. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  781. filepath = `/change/download/file/${fileInfo.id}`;
  782. } else {
  783. filepath = filepath.replace(/^app|\/app/, '');
  784. }
  785. fileInfo.filepath && (responseData.data = { filepath });
  786. }
  787. } catch (error) {
  788. this.log(error);
  789. this.setMessage(error.toString(), this.messageType.ERROR);
  790. responseData.err = 1;
  791. responseData.msg = error.toString();
  792. }
  793. }
  794. ctx.body = responseData;
  795. }
  796. /**
  797. * 删除变更令
  798. * @param {Object} ctx - egg全局变量
  799. * @return {void}
  800. */
  801. async delete(ctx) {
  802. try {
  803. const result = await ctx.service.change.delete(ctx.request.body.cid);
  804. if (!result) {
  805. throw '删除变更令失败';
  806. }
  807. ctx.redirect(ctx.request.header.referer);
  808. } catch (err) {
  809. console.log(err);
  810. ctx.redirect(ctx.request.header.referer);
  811. }
  812. }
  813. /**
  814. * 变更令重新审批
  815. * @param {Object} ctx - egg全局变量
  816. * @return {void}
  817. */
  818. async checkAgain(ctx) {
  819. try {
  820. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  821. if (!changeData) {
  822. throw '变更令数据错误';
  823. }
  824. // 获取终审
  825. const auditInfo = (await this.ctx.service.changeAudit.getAllDataByCondition({ where: { cid: changeData.cid }, orders: [['usort', 'desc']], limit: 1, offset: 0 }))[0];
  826. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== auditInfo.uid) {
  827. throw '您无权进行该操作';
  828. }
  829. if (ctx.session.sessionUser.loginStatus === 0) {
  830. const code = ctx.request.body.code;
  831. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  832. if (!pa.auth_mobile) {
  833. throw '未绑定手机号';
  834. }
  835. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  836. const cacheCode = await app.redis.get(cacheKey);
  837. // console.log(cacheCode);
  838. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  839. throw '验证码不正确!';
  840. }
  841. }
  842. // 重新审批
  843. const result = await ctx.service.change.checkAgain(changeData.cid);
  844. if (!result) {
  845. throw '重新审批失败';
  846. }
  847. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  848. ctx.body = {
  849. err: 0,
  850. url: ctx.request.header.referer,
  851. msg: '',
  852. };
  853. } catch (err) {
  854. console.log(err);
  855. // ctx.redirect(ctx.request.header.referer);
  856. ctx.body = {
  857. err: 1,
  858. // url: ctx.request.header.referer,
  859. msg: err,
  860. };
  861. }
  862. }
  863. /**
  864. * 获取变更清单
  865. * @param ctx
  866. * @return {Promise<void>}
  867. */
  868. async bills(ctx) {
  869. try {
  870. const data = JSON.parse(ctx.request.body.data);
  871. const responseData = { err: 0, msg: '', data: [] };
  872. switch (data.type) {
  873. case 'gather':
  874. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  875. break;
  876. default:
  877. throw '查询的数据不存在';
  878. }
  879. ctx.body = responseData;
  880. } catch (err) {
  881. this.log(err);
  882. this.ajaxErrorBody(err, '获取变更清单失败');
  883. }
  884. }
  885. /**
  886. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  887. * @param ctx
  888. * @return {Promise<void>}
  889. */
  890. async checkCodeRepeat(ctx) {
  891. const responseData = {
  892. err: 0,
  893. msg: '',
  894. data: '',
  895. };
  896. try {
  897. const tenderId = ctx.params.id;
  898. const cid = ctx.params.cid;
  899. const data = JSON.parse(ctx.request.body.data);
  900. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  901. if (result) {
  902. throw '该变更令号(批复编号)已使用';
  903. }
  904. } catch (err) {
  905. responseData.err = 1;
  906. responseData.msg = err;
  907. }
  908. ctx.body = responseData;
  909. }
  910. }
  911. return ChangeController;
  912. };