change_controller.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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 stageChangeNum = await ctx.service.stageChange.count({ cid: change.cid });
  473. const stageChangeNum2 = await ctx.service.stageChange.count({ cid: change.cid, qty: null });
  474. renderData.stageChangeNum = stageChangeNum - stageChangeNum2;
  475. await this.layout('change/info.ejs', renderData, 'change/info_modal.ejs');
  476. } catch (err) {
  477. this.log(err);
  478. ctx.redirect('/tender/' + ctx.params.id + '/change');
  479. }
  480. }
  481. async defaultBills(ctx) {
  482. try {
  483. const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  484. const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  485. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  486. ctx.body = { err: 0, msg: '', data: { bills: ledgerData, pos: posData, dealBills } };
  487. } catch (err) {
  488. this.log(err);
  489. ctx.body = { err: 1, msg: err.toString(), data: [] };
  490. }
  491. }
  492. /**
  493. * 变更令上报和保存
  494. * @param {Object} ctx - egg全局变量
  495. * @return {void}
  496. */
  497. async save(ctx) {
  498. // 变更令信息
  499. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  500. try {
  501. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  502. if (!result) {
  503. throw '上报失败';
  504. }
  505. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  506. ctx.body = { err: 0, msg: '保存成功' };
  507. } else {
  508. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  509. }
  510. } catch (err) {
  511. this.log(err);
  512. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  513. ctx.body = { err: 1, msg: err.toString() };
  514. } else {
  515. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  516. }
  517. }
  518. }
  519. /**
  520. * 变更令审批
  521. * @param {Object} ctx - egg全局变量
  522. * @return {void}
  523. */
  524. async approval(ctx) {
  525. try {
  526. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.change_id });
  527. if (!changeData) {
  528. throw '变更令数据错误';
  529. }
  530. const status = parseInt(ctx.request.body.status);
  531. let result = false;
  532. const pid = this.ctx.session.sessionProject.id;
  533. switch (status) {
  534. case 3:// 审批通过
  535. result = await ctx.service.change.approvalSuccess(pid, ctx.request.body, changeData);
  536. break;
  537. case 4:// 审批终止
  538. result = await ctx.service.change.approvalStop(ctx.request.body);
  539. break;
  540. case 5:// 审批退回到原报人
  541. result = await ctx.service.change.approvalBack(pid, ctx.request.body, changeData);
  542. break;
  543. case 6:// 审批退回到上一个审批人
  544. result = await ctx.service.change.approvalBackNew(pid, ctx.request.body, changeData);
  545. break;
  546. default:break;
  547. }
  548. if (!result) {
  549. throw '审批失败';
  550. }
  551. ctx.redirect(ctx.request.header.referer);
  552. } catch (err) {
  553. console.log(err);
  554. ctx.redirect(ctx.request.header.referer);
  555. }
  556. }
  557. /**
  558. * 变更公司管理
  559. * @param {Object} ctx - egg全局变量
  560. * @return {void}
  561. */
  562. async updateCompany(ctx) {
  563. const responseData = {
  564. err: 0,
  565. msg: '',
  566. data: '',
  567. };
  568. try {
  569. const data = JSON.parse(ctx.request.body.data);
  570. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  571. throw '参数有误';
  572. }
  573. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  574. responseData.data = { add: addCompany, select: selectCompany };
  575. } catch (err) {
  576. responseData.err = 1;
  577. responseData.msg = err;
  578. }
  579. ctx.body = responseData;
  580. }
  581. /**
  582. * 上传附件
  583. * @param {Object} ctx - egg全局变量
  584. * @return {void}
  585. */
  586. async uploadFile(ctx) {
  587. const responseData = {
  588. err: 0,
  589. msg: '',
  590. data: [],
  591. };
  592. let stream;
  593. try {
  594. const parts = ctx.multipart({ autoFields: true });
  595. const files = [];
  596. let index = 0;
  597. while ((stream = await parts()) !== undefined) {
  598. // 判断用户是否选择上传文件
  599. if (!stream.filename) {
  600. throw '请选择上传的文件!';
  601. }
  602. // const create_time = Date.parse(new Date()) / 1000;
  603. // const fileInfo = path.parse(stream.filename);
  604. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  605. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  606. // // 判断文件夹是否存在,不存在则直接创建文件夹
  607. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  608. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  609. // }
  610. // // 保存文件
  611. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  612. const fileInfo = path.parse(stream.filename);
  613. const create_time = Date.parse(new Date()) / 1000;
  614. const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  615. await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  616. await sendToWormhole(stream);
  617. // 保存数据到att表
  618. const fileData = {
  619. in_time: create_time,
  620. filename: fileInfo.name,
  621. fileext: fileInfo.ext,
  622. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  623. filepath,
  624. };
  625. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  626. if (!result) {
  627. throw '导入数据库保存失败';
  628. }
  629. fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  630. fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  631. fileData.id = result.insertId;
  632. delete fileData.filepath;
  633. files.push(fileData);
  634. ++index;
  635. }
  636. responseData.data = files;
  637. } catch (err) {
  638. this.log(err);
  639. // 失败需要消耗掉stream 以防卡死
  640. if (stream) {
  641. await sendToWormhole(stream);
  642. }
  643. this.setMessage(err.toString(), this.messageType.ERROR);
  644. }
  645. ctx.body = responseData;
  646. }
  647. /**
  648. * 下载附件
  649. * @param {Object} ctx - egg全局变量
  650. * @return {void}
  651. */
  652. async downloadFile(ctx) {
  653. const id = ctx.params.id;
  654. if (id) {
  655. try {
  656. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  657. if (fileInfo !== undefined && fileInfo !== '') {
  658. const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  659. // 解决中文无法下载问题
  660. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  661. let disposition = '';
  662. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  663. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  664. } else if (userAgent.indexOf('firefox') >= 0) {
  665. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  666. } else {
  667. /* safari等其他非主流浏览器只能自求多福了 */
  668. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  669. }
  670. ctx.response.set({
  671. 'Content-Type': 'application/octet-stream',
  672. 'Content-Disposition': disposition,
  673. 'Content-Length': fileInfo.filesize,
  674. });
  675. ctx.body = await fs.createReadStream(fileName);
  676. } else {
  677. throw '不存在该文件';
  678. }
  679. } catch (err) {
  680. this.log(err);
  681. this.setMessage(err.toString(), this.messageType.ERROR);
  682. }
  683. }
  684. }
  685. /**
  686. * 删除附件
  687. * @param {Object} ctx - egg全局变量
  688. * @return {void}
  689. */
  690. async deleteFile(ctx) {
  691. const responseData = {
  692. err: 0,
  693. msg: '',
  694. data: '',
  695. };
  696. try {
  697. const data = JSON.parse(ctx.request.body.data);
  698. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  699. if (fileInfo !== undefined && fileInfo !== '') {
  700. // 先删除文件
  701. await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  702. // 再删除数据库
  703. await ctx.service.changeAtt.deleteById(data.id);
  704. responseData.data = '';
  705. } else {
  706. throw '不存在该文件';
  707. }
  708. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  709. // throw '参数有误';
  710. // }
  711. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  712. // responseData.data = { add: addCompany, select: selectCompany };
  713. } catch (err) {
  714. responseData.err = 1;
  715. responseData.msg = err;
  716. }
  717. ctx.body = responseData;
  718. }
  719. /**
  720. * 查看附件
  721. * @param {Object} ctx - egg全局变量
  722. * @return {void}
  723. */
  724. async checkFile(ctx) {
  725. const responseData = { err: 0, msg: '' };
  726. const id = parseInt(ctx.params.id);
  727. if (id) {
  728. try {
  729. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  730. if (fileInfo && Object.keys(fileInfo).length) {
  731. let filepath = fileInfo.filepath;
  732. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  733. filepath = `/change/download/file/${fileInfo.id}`;
  734. } else {
  735. filepath = filepath.replace(/^app|\/app/, '');
  736. }
  737. fileInfo.filepath && (responseData.data = { filepath });
  738. }
  739. } catch (error) {
  740. this.log(error);
  741. this.setMessage(error.toString(), this.messageType.ERROR);
  742. responseData.err = 1;
  743. responseData.msg = error.toString();
  744. }
  745. }
  746. ctx.body = responseData;
  747. }
  748. /**
  749. * 删除变更令
  750. * @param {Object} ctx - egg全局变量
  751. * @return {void}
  752. */
  753. async delete(ctx) {
  754. try {
  755. const result = await ctx.service.change.delete(ctx.request.body.cid);
  756. if (!result) {
  757. throw '删除变更令失败';
  758. }
  759. ctx.redirect(ctx.request.header.referer);
  760. } catch (err) {
  761. console.log(err);
  762. ctx.redirect(ctx.request.header.referer);
  763. }
  764. }
  765. /**
  766. * 变更令重新审批
  767. * @param {Object} ctx - egg全局变量
  768. * @return {void}
  769. */
  770. async checkAgain(ctx) {
  771. try {
  772. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  773. if (!changeData) {
  774. throw '变更令数据错误';
  775. }
  776. // 获取终审
  777. const auditInfo = (await this.ctx.service.changeAudit.getAllDataByCondition({ where: { cid: changeData.cid }, orders: [['usort', 'desc']], limit: 1, offset: 0 }))[0];
  778. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== auditInfo.uid) {
  779. throw '您无权进行该操作';
  780. }
  781. if (ctx.session.sessionUser.loginStatus === 0) {
  782. const code = ctx.request.body.code;
  783. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  784. if (!pa.auth_mobile) {
  785. throw '未绑定手机号';
  786. }
  787. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  788. const cacheCode = await app.redis.get(cacheKey);
  789. // console.log(cacheCode);
  790. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  791. throw '验证码不正确!';
  792. }
  793. }
  794. // 重新审批
  795. const result = await ctx.service.change.checkAgain(changeData.cid);
  796. if (!result) {
  797. throw '重新审批失败';
  798. }
  799. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  800. ctx.body = {
  801. err: 0,
  802. url: ctx.request.header.referer,
  803. msg: '',
  804. };
  805. } catch (err) {
  806. console.log(err);
  807. // ctx.redirect(ctx.request.header.referer);
  808. ctx.body = {
  809. err: 1,
  810. // url: ctx.request.header.referer,
  811. msg: err,
  812. };
  813. }
  814. }
  815. /**
  816. * 获取变更清单
  817. * @param ctx
  818. * @return {Promise<void>}
  819. */
  820. async bills(ctx) {
  821. try {
  822. const data = JSON.parse(ctx.request.body.data);
  823. const responseData = { err: 0, msg: '', data: [] };
  824. switch (data.type) {
  825. case 'gather':
  826. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  827. break;
  828. default:
  829. throw '查询的数据不存在';
  830. }
  831. ctx.body = responseData;
  832. } catch (err) {
  833. this.log(err);
  834. this.ajaxErrorBody(err, '获取变更清单失败');
  835. }
  836. }
  837. /**
  838. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  839. * @param ctx
  840. * @return {Promise<void>}
  841. */
  842. async checkCodeRepeat(ctx) {
  843. const responseData = {
  844. err: 0,
  845. msg: '',
  846. data: '',
  847. };
  848. try {
  849. const tenderId = ctx.params.id;
  850. const cid = ctx.params.cid;
  851. const data = JSON.parse(ctx.request.body.data);
  852. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  853. if (result) {
  854. throw '该变更令号(批复编号)已使用';
  855. }
  856. } catch (err) {
  857. responseData.err = 1;
  858. responseData.msg = err;
  859. }
  860. ctx.body = responseData;
  861. }
  862. }
  863. return ChangeController;
  864. };