change_controller.js 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2018/8/14
  7. * @version
  8. */
  9. const moment = require('moment');
  10. const sendToWormhole = require('stream-wormhole');
  11. const fs = require('fs');
  12. const path = require('path');
  13. const audit = require('../const/audit');
  14. const codeRuleConst = require('../const/code_rule');
  15. const changeConst = require('../const/change');
  16. const accountGroup = require('../const/account_group').group;
  17. const shenpiConst = require('../const/shenpi');
  18. // const tenderMenu = require('../../config/menu').tenderMenu;
  19. module.exports = app => {
  20. class ChangeController extends app.BaseController {
  21. /**
  22. * 构造函数
  23. *
  24. * @param {Object} ctx - egg全局变量
  25. * @return {void}
  26. */
  27. constructor(ctx) {
  28. super(ctx);
  29. ctx.showProject = true;
  30. ctx.showTender = true;
  31. ctx.showTitle = true;
  32. }
  33. async _filterChanges(ctx, status = 0) {
  34. const tenderId = ctx.params.id;
  35. ctx.session.sessionUser.tenderId = tenderId;
  36. const tender = await this.service.tender.getDataById(tenderId);
  37. // const tenderList = await this.service.tender.getList();
  38. const page = ctx.page;
  39. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  40. const orders = ctx.query.order ? ctx.query.order : 0;
  41. const changes = await ctx.service.change.getListByStatus(tender.id, status, 1, sorts, orders);
  42. const total = await ctx.service.change.getCountByStatus(tender.id, status);
  43. if (changes !== null) {
  44. let i = 0;
  45. for (const c of changes) {
  46. const status = c.status === audit.flow.status.uncheck ? 0 : 1;
  47. // 根据审批人对当前变更令的状态取不同的展示方式。
  48. let changeAudit = '';
  49. let auditStatus = 0;
  50. switch (c.status) {
  51. case 1:
  52. auditStatus = 1;
  53. break;
  54. case 2:
  55. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  56. auditStatus = changeAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  57. break;
  58. case 3:
  59. case 4:
  60. auditStatus = 0;
  61. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  62. break;
  63. case 5:
  64. changeAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times - 1, status);
  65. auditStatus = c.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  66. const back_changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, c.cid);
  67. c.stageChangeNum = this.ctx.helper.sum(back_changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  68. break;
  69. case 6:
  70. changeAudit = await ctx.service.changeAudit.getLastBackUser(c.cid, c.times);
  71. const checkingAudit = await ctx.service.changeAudit.getLastUser(c.cid, c.times, status);
  72. auditStatus = checkingAudit.uid === ctx.session.sessionUser.accountId ? 1 : 0;
  73. break;
  74. case 9:
  75. auditStatus = 9;
  76. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, c.cid);
  77. c.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  78. break;
  79. default:
  80. break;
  81. }
  82. changes[i].changeAudit = changeAudit;
  83. changes[i].auditStatus = auditStatus;
  84. i++;
  85. }
  86. }
  87. // 分页相关
  88. const pageInfo = {
  89. page,
  90. total: Math.ceil(total / app.config.pageSize),
  91. queryData: JSON.stringify(ctx.urlInfo.query),
  92. };
  93. const filter = JSON.parse(JSON.stringify(audit.filter));
  94. filter.count = [];
  95. 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);
  96. 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);
  97. 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);
  98. 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);
  99. 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);
  100. const codeRule = tender.c_rule ? JSON.parse(tender.c_rule) : [];
  101. for (const rule of codeRule) {
  102. switch (rule.rule_type) {
  103. case codeRuleConst.measure.ruleType.dealCode:
  104. rule.preview = ctx.tender.info.deal_info.dealCode;
  105. break;
  106. case codeRuleConst.measure.ruleType.tenderName:
  107. rule.preview = tender.name;
  108. break;
  109. case codeRuleConst.measure.ruleType.inDate:
  110. rule.preview = moment().format('YYYY');
  111. break;
  112. case codeRuleConst.measure.ruleType.text:
  113. rule.preview = rule.text;
  114. break;
  115. case codeRuleConst.measure.ruleType.addNo:
  116. const s = '0000000000';
  117. rule.preview = s.substr(s.length - rule.format);
  118. break;
  119. default: break;
  120. }
  121. }
  122. const renderData = {
  123. uid: ctx.session.sessionUser.accountId,
  124. moment,
  125. tender,
  126. // tenderList,
  127. pageInfo,
  128. changes,
  129. filter,
  130. status,
  131. codeRule,
  132. dealCode: ctx.tender.info.deal_info.dealCode,
  133. auditConst: audit.flow,
  134. changeConst,
  135. ruleType: codeRuleConst.ruleType.change,
  136. ruleConst: codeRuleConst.measure,
  137. tenderMenu: this.menu.tenderMenu,
  138. preUrl: '/tender/' + tenderId,
  139. tpUnit: ctx.tender.info.decimal.tp,
  140. };
  141. await this.layout('change/index.ejs', renderData, 'change/modal.ejs');
  142. }
  143. /**
  144. * 变更管理 页面 (Get)
  145. *
  146. * @param {Object} ctx - egg全局变量
  147. * @return {void}
  148. */
  149. async index(ctx) {
  150. try {
  151. await this._filterChanges(ctx);
  152. } catch (err) {
  153. this.log(err);
  154. ctx.redirect('/dashboard');
  155. }
  156. }
  157. /**
  158. *
  159. * @param {Object} ctx - egg全局变量
  160. * @return {void}
  161. */
  162. async newCode(ctx) {
  163. const responseData = {
  164. err: 0,
  165. msg: '',
  166. data: '',
  167. };
  168. try {
  169. const tenderId = ctx.params.id;
  170. if (!tenderId) {
  171. throw '当前未打开标段';
  172. }
  173. const tenderData = await ctx.service.tender.getDataById(tenderId);
  174. const cCodeRule = tenderData.c_rule !== null ? JSON.parse(tenderData.c_rule) : [];
  175. const code = [];
  176. for (const rule of cCodeRule) {
  177. switch (rule.rule_type) {
  178. case codeRuleConst.measure.ruleType.dealCode:
  179. code.push(ctx.tender.info.deal_info.dealCode);
  180. break;
  181. case codeRuleConst.measure.ruleType.tenderName:
  182. code.push(tenderData.name);
  183. break;
  184. case codeRuleConst.measure.ruleType.text:
  185. code.push(rule.text);
  186. break;
  187. case codeRuleConst.measure.ruleType.inDate:
  188. code.push(moment().format('YYYY'));
  189. break;
  190. case codeRuleConst.measure.ruleType.addNo:
  191. let s = '0000000000';
  192. const count = rule.start + await ctx.service.change.count({ tid: tenderId });
  193. s = s + count;
  194. code.push(s.substr(s.length - rule.format));
  195. break;
  196. default: break;
  197. }
  198. }
  199. responseData.data = code.join(tenderData.c_connector !== null && tenderData.c_connector !== 3 ? codeRuleConst.measure.connectorString[tenderData.c_connector] : '');
  200. } catch (err) {
  201. responseData.err = 1;
  202. responseData.msg = err;
  203. }
  204. ctx.body = responseData;
  205. }
  206. /**
  207. * 新增变更 (Post)
  208. *
  209. * @param {Object} ctx - egg全局变量
  210. * @return {void}
  211. */
  212. async add(ctx) {
  213. try {
  214. const tenderId = ctx.params.id;
  215. if (!tenderId) {
  216. throw '当前未打开标段';
  217. }
  218. const data = JSON.parse(ctx.request.body.data);
  219. if (!data.code || data.code === '' || !data.name || data.name === '') {
  220. throw '变更令号不能为空';
  221. }
  222. const change = await ctx.service.change.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  223. ctx.body = { err: 0, msg: '', data: change };
  224. } catch (err) {
  225. this.log(err);
  226. ctx.body = { err: 1, msg: err.toString() };
  227. }
  228. }
  229. /**
  230. * 变更管理 状态筛选 页面 (Get)
  231. * @param {Object} ctx - egg全局变量
  232. * @return {void}
  233. */
  234. async status(ctx) {
  235. try {
  236. const status = parseInt(ctx.params.status);
  237. await this._filterChanges(ctx, status);
  238. } catch (err) {
  239. this.logger.error(err);
  240. ctx.redirect('/tender/' + ctx.params.id + '/change');
  241. }
  242. }
  243. /**
  244. * 变更信息 页面 (Get)
  245. *
  246. * @param {Object} ctx - egg全局变量
  247. * @return {void}
  248. */
  249. async info(ctx) {
  250. try {
  251. const whiteList = this.ctx.app.config.multipart.whitelist;
  252. const tenderid = ctx.params.id !== undefined ? ctx.params.id : ctx.session.sessionUser.tenderId;
  253. ctx.session.sessionUser.tenderId = tenderid;
  254. const tender = await ctx.service.tender.getDataById(tenderid);
  255. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  256. // 后台判断当前人查看info状态
  257. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  258. // 获取附件列表
  259. const attList = await ctx.service.changeAtt.getChangeAttachment(ctx.params.cid);
  260. // 获取其他变更令数据
  261. const othersChange = await ctx.service.change.getOthersChange(ctx.params.id, ctx.params.cid);
  262. // 根据auditStatus获取审批人列表
  263. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  264. // 获取已选清单
  265. let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  266. // 获取用户人验证手机号
  267. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  268. const auth_mobile = pa.auth_mobile;
  269. const renderData = {
  270. uid: ctx.session.sessionUser.accountId,
  271. tender,
  272. change,
  273. othersChange,
  274. changeConst,
  275. auditStatus,
  276. auditConst: audit.flow,
  277. ledgerConsts: audit.ledger.status,
  278. attList,
  279. whiteList,
  280. auditList,
  281. changeList,
  282. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  283. upUnit: ctx.tender.info.decimal.up,
  284. authMobile: auth_mobile,
  285. shenpiConst,
  286. };
  287. // 根据auditStatus状态获取的不同的数据
  288. if (auditStatus === 1 || auditStatus === 2 || auditStatus === 9) {
  289. renderData.changeUnits = changeConst.units;
  290. renderData.precision = ctx.tender.info.precision;
  291. // renderData.accountGroup = accountGroup;
  292. // 获取所有项目参与者
  293. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  294. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  295. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  296. });
  297. renderData.accountList = accountList;
  298. renderData.accountGroup = accountGroup.map((item, idx) => {
  299. const groupList = accountList.filter(item => item.account_group === idx);
  300. return { groupName: item, groupList };
  301. });
  302. // 重新上报获取审批流程
  303. if (auditStatus === 2 || auditStatus === 9) {
  304. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  305. // 展示页右侧审批流程列表
  306. const auditList3 = [];
  307. for (let time = 1; time <= change.times - 1; time++) {
  308. const auditTimeList = [];
  309. let max_sort = 1;
  310. for (const al of auditList2) {
  311. if (al.times === time) {
  312. auditTimeList.push(al);
  313. if (al.usite > max_sort) {
  314. max_sort = al.usite;
  315. }
  316. }
  317. }
  318. for (const i in auditTimeList) {
  319. auditTimeList[i].max_sort = max_sort;
  320. }
  321. auditList3.push(auditTimeList);
  322. }
  323. renderData.auditList3 = auditList3;
  324. }
  325. // 根据清单获取提交数据和计算总金额
  326. const changeListData = [];
  327. const changeWhiteListData = [];
  328. let ototalCost = 0;
  329. let ctotalCost = 0;
  330. for (const cl of changeList) {
  331. const cLArray = [
  332. cl.code,
  333. cl.name,
  334. cl.bwmx,
  335. cl.unit,
  336. cl.unit_price,
  337. cl.oamount,
  338. cl.camount,
  339. cl.detail,
  340. cl.lid,
  341. cl.xmj_code,
  342. cl.xmj_jldy,
  343. cl.gcl_id,
  344. ];
  345. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, ctx.tender.info.decimal.tp);
  346. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, ctx.tender.info.decimal.tp);
  347. if (cl.lid !== '0') {
  348. changeListData.push(cLArray.join('*;*'));
  349. } else {
  350. changeWhiteListData.push(cLArray.join('*;*'));
  351. }
  352. }
  353. renderData.changeListData = changeListData.join('^_^');
  354. renderData.changeWhiteListData = changeWhiteListData.join('^_^');
  355. renderData.ototalCost = ototalCost;
  356. renderData.ctotalCost = ctotalCost;
  357. // 获取公司列表
  358. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: tenderid } });
  359. renderData.companyList = companyList;
  360. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7) {
  361. // 展示页左侧审批流程列表和清单审批列表数据
  362. const times = change.status === audit.flow.status.back ?
  363. change.times - 1 : change.times;
  364. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  365. // 展示页右侧审批流程列表
  366. const auditList3 = [];
  367. for (let time = 1; time <= times; time++) {
  368. const auditTimeList = [];
  369. let max_sort = 1;
  370. for (const al of auditList) {
  371. if (al.times === time) {
  372. auditTimeList.push(al);
  373. if (al.usite > max_sort) {
  374. max_sort = al.usite;
  375. }
  376. }
  377. }
  378. for (const i in auditTimeList) {
  379. auditTimeList[i].max_sort = max_sort;
  380. }
  381. auditList3.push(auditTimeList);
  382. }
  383. renderData.auditList3 = auditList3;
  384. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  385. renderData.changeList = changeList;
  386. let ototalCost = 0;
  387. let ctotalCost = 0;
  388. let stotalCost = 0;
  389. const auditTotalCost = [];
  390. for (const cl of changeList) {
  391. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  392. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  393. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  394. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  395. // stotalCost += cl.samount !== '' && cl.unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.samount), renderData.tpUnit)) : 0;
  396. stotalCost += cl.samount !== '' && cl.unit_price !== null ? ctx.helper.mul(cl.unit_price, cl.samount, renderData.tpUnit) : 0;
  397. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  398. auditTotalCost.push(audit_amount);
  399. }
  400. renderData.ototalCost = ototalCost;
  401. renderData.ctotalCost = ctotalCost;
  402. renderData.stotalCost = stotalCost;
  403. // 清单表页赋值
  404. for (const [index, au] of auditList2.entries()) {
  405. if (au.usite !== 0) {
  406. au.list_amount = [];
  407. au.totalCost = 0;
  408. for (const [auindex, at] of auditTotalCost.entries()) {
  409. au.list_amount.push(at[index - 1]);
  410. // 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;
  411. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  412. }
  413. }
  414. }
  415. renderData.auditList2 = auditList2;
  416. } else if (auditStatus === 6) {
  417. // 展示页左侧审批流程列表和清单审批列表数据
  418. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  419. renderData.auditList2 = auditList2;
  420. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  421. for (const i in auditList3) {
  422. auditList3[i].max_sort = auditList2.length - 1;
  423. }
  424. renderData.auditList3 = auditList3;
  425. // 展示页右侧审批流程列表
  426. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  427. const auditList4 = [];
  428. for (let time = 1; time <= change.times; time++) {
  429. const auditTimeList = [];
  430. let max_sort = 1;
  431. for (const al of auditList5) {
  432. if (al.times === time) {
  433. auditTimeList.push(al);
  434. if (al.usite > max_sort) {
  435. max_sort = al.usite;
  436. }
  437. }
  438. }
  439. for (const i in auditTimeList) {
  440. auditTimeList[i].max_sort = max_sort;
  441. }
  442. if (auditTimeList.length > 0) {
  443. auditList4.push(auditTimeList);
  444. }
  445. }
  446. renderData.auditList4 = auditList4;
  447. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  448. renderData.changeList = changeList;
  449. let ototalCost = 0;
  450. let ctotalCost = 0;
  451. const auditTotalCost = [];
  452. const auditUnit = [];
  453. for (const cl of changeList) {
  454. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  455. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  456. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  457. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  458. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  459. auditTotalCost.push(audit_amount);
  460. }
  461. renderData.ototalCost = ototalCost;
  462. renderData.ctotalCost = ctotalCost;
  463. // 清单表页赋值
  464. for (const [index, au] of auditList.entries()) {
  465. if (au.usite !== 0) {
  466. au.list_amount = [];
  467. au.totalCost = 0;
  468. if (au.uid === renderData.uid) {
  469. for (const [auindex, at] of auditTotalCost.entries()) {
  470. // if (at[index - 2] !== undefined) {
  471. // au.list_amount.push(at[index - 2]);
  472. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 2]), renderData.tpUnit));
  473. // } else if (at[index - 2] === undefined) {
  474. // au.list_amount.push(changeList[auindex].camount);
  475. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].camount), renderData.tpUnit));
  476. // }
  477. au.list_amount.push(changeList[auindex].spamount);
  478. // au.totalCost += changeList[auindex].unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].spamount), renderData.tpUnit));
  479. au.totalCost += changeList[auindex].unit_price === null ? 0 : ctx.helper.mul(changeList[auindex].unit_price, changeList[auindex].spamount, renderData.tpUnit);
  480. }
  481. } else {
  482. for (const [auindex, at] of auditTotalCost.entries()) {
  483. au.list_amount.push(at[index - 1]);
  484. // 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;
  485. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  486. }
  487. }
  488. }
  489. }
  490. }
  491. renderData.auditList = auditList;
  492. // 获取是否已存在调用变更令
  493. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  494. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  495. await this.layout('change/info.ejs', renderData, 'change/info_modal.ejs');
  496. } catch (err) {
  497. this.log(err);
  498. ctx.redirect('/tender/' + ctx.params.id + '/change');
  499. }
  500. }
  501. /**
  502. * 变更信息 新版本页面 (Get)
  503. *
  504. * @param {Object} ctx - egg全局变量
  505. * @return {void}
  506. */
  507. async information(ctx) {
  508. try {
  509. const whiteList = this.ctx.app.config.multipart.whitelist;
  510. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  511. const change = ctx.change;
  512. // 后台判断当前人查看info状态
  513. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  514. // 获取附件列表
  515. const attList = await ctx.service.changeAtt.getChangeAttachment(change.cid, 'desc');
  516. // 获取其他变更令数据
  517. const othersChange = await ctx.service.change.getOthersChange(ctx.tender.id, change.cid);
  518. // 根据auditStatus获取审批人列表
  519. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  520. // 获取用户人验证手机号
  521. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  522. const auth_mobile = pa.auth_mobile;
  523. const renderData = {
  524. tender,
  525. change,
  526. othersChange,
  527. changeConst,
  528. auditStatus,
  529. auditConst: audit.flow,
  530. ledgerConsts: audit.ledger.status,
  531. attList,
  532. whiteList,
  533. auditList,
  534. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  535. upUnit: ctx.tender.info.decimal.up,
  536. authMobile: auth_mobile,
  537. shenpiConst,
  538. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.information),
  539. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  540. precision: ctx.tender.info.precision,
  541. };
  542. // 根据auditStatus状态获取的不同的数据
  543. if (auditStatus === 1 || auditStatus === 2 || auditStatus === 9) {
  544. renderData.changeUnits = changeConst.units;
  545. // renderData.accountGroup = accountGroup;
  546. // 获取所有项目参与者
  547. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  548. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  549. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  550. });
  551. renderData.accountList = accountList;
  552. renderData.accountGroup = accountGroup.map((item, idx) => {
  553. const groupList = accountList.filter(item => item.account_group === idx);
  554. return { groupName: item, groupList };
  555. });
  556. // 重新上报获取审批流程
  557. if (auditStatus === 2 || auditStatus === 9) {
  558. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  559. // 展示页右侧审批流程列表
  560. const auditList3 = [];
  561. for (let time = 1; time <= change.times - 1; time++) {
  562. const auditTimeList = [];
  563. let max_sort = 1;
  564. for (const al of auditList2) {
  565. if (al.times === time) {
  566. auditTimeList.push(al);
  567. if (al.usite > max_sort) {
  568. max_sort = al.usite;
  569. }
  570. }
  571. }
  572. for (const i in auditTimeList) {
  573. auditTimeList[i].max_sort = max_sort;
  574. }
  575. auditList3.push(auditTimeList);
  576. }
  577. renderData.auditList3 = auditList3;
  578. }
  579. // 获取公司列表
  580. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  581. renderData.companyList = companyList;
  582. // 获取已选清单
  583. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  584. renderData.changeList = changeList;
  585. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7 || auditStatus === 8) {
  586. // 展示页左侧审批流程列表和清单审批列表数据
  587. const times = change.status === audit.flow.status.back ?
  588. change.times - 1 : change.times;
  589. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  590. // 展示页右侧审批流程列表
  591. const auditList3 = [];
  592. for (let time = 1; time <= times; time++) {
  593. const auditTimeList = [];
  594. let max_sort = 1;
  595. for (const al of auditList) {
  596. if (al.times === time) {
  597. auditTimeList.push(al);
  598. if (al.usite > max_sort) {
  599. max_sort = al.usite;
  600. }
  601. }
  602. }
  603. for (const i in auditTimeList) {
  604. auditTimeList[i].max_sort = max_sort;
  605. }
  606. auditList3.push(auditTimeList);
  607. }
  608. renderData.auditList3 = auditList3;
  609. // 获取已选清单
  610. // let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  611. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  612. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  613. for (const cl of changeList) {
  614. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  615. // 清单表页赋值
  616. for (const [index, au] of auditList2.entries()) {
  617. if (au.usite !== 0) {
  618. cl['audit_amount_' + au.uid] = audit_amount[index - 1] ? audit_amount[index - 1] : null;
  619. }
  620. }
  621. }
  622. renderData.changeList = changeList;
  623. renderData.auditList2 = auditList2;
  624. } else if (auditStatus === 6) {
  625. // 展示页左侧审批流程列表和清单审批列表数据
  626. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  627. renderData.auditList2 = auditList2;
  628. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  629. for (const i in auditList3) {
  630. auditList3[i].max_sort = auditList2.length - 1;
  631. }
  632. renderData.auditList3 = auditList3;
  633. // 展示页右侧审批流程列表
  634. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  635. const auditList4 = [];
  636. for (let time = 1; time <= change.times; time++) {
  637. const auditTimeList = [];
  638. let max_sort = 1;
  639. for (const al of auditList5) {
  640. if (al.times === time) {
  641. auditTimeList.push(al);
  642. if (al.usite > max_sort) {
  643. max_sort = al.usite;
  644. }
  645. }
  646. }
  647. for (const i in auditTimeList) {
  648. auditTimeList[i].max_sort = max_sort;
  649. }
  650. if (auditTimeList.length > 0) {
  651. auditList4.push(auditTimeList);
  652. }
  653. }
  654. renderData.auditList4 = auditList4;
  655. // 获取已选清单
  656. // let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  657. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  658. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  659. for (const cl of changeList) {
  660. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  661. // 清单表页赋值
  662. for (const [index, au] of auditList2.entries()) {
  663. if (au.usite !== 0) {
  664. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  665. }
  666. }
  667. }
  668. renderData.changeList = changeList;
  669. }
  670. renderData.auditList = auditList;
  671. // 获取是否已存在调用变更令
  672. let changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  673. changeUsedData = ctx.helper._.filter(changeUsedData, function(item) {
  674. return item.used_qty !== null;
  675. })
  676. renderData.changeUsedData = changeUsedData;
  677. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  678. await this.layout('change/information.ejs', renderData, 'change/information_modal.ejs');
  679. } catch (err) {
  680. this.log(err);
  681. ctx.redirect('/tender/' + ctx.params.id + '/change');
  682. }
  683. }
  684. /**
  685. * 变更清单 - 操作 (Ajax)
  686. * @param ctx
  687. * @return {Promise<void>}
  688. */
  689. async saveListsData(ctx) {
  690. try {
  691. const data = JSON.parse(ctx.request.body.data);
  692. const responseData = {
  693. err: 0,
  694. msg: '',
  695. data: {},
  696. };
  697. switch (data.type) {
  698. case 'add':
  699. responseData.data = await ctx.service.changeAuditList.add(data.postData);
  700. break;
  701. case 'batchadd':
  702. responseData.data = await ctx.service.changeAuditList.batchAdd(data);
  703. break;
  704. case 'del':
  705. await ctx.service.changeAuditList.del(data.id);
  706. break;
  707. case 'update':
  708. await ctx.service.changeAuditList.save(data.updateData);
  709. break;
  710. case 'paste':
  711. await ctx.service.changeAuditList.saveDatas(data.updateData);
  712. // 取所有工料表
  713. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  714. break;
  715. case 'ledger_list':
  716. await ctx.service.changeAuditList.saveLedgerListDatas(data.updateData);
  717. // 取所有工料表
  718. responseData.data = { changeList: await ctx.service.changeAuditList.getList(ctx.change.cid),
  719. usedList: await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, ctx.change.cid) };
  720. break;
  721. case 'remove_list':
  722. await ctx.service.changeAuditList.removeLedgerListDatas(data.updateData);
  723. // 取所有工料表
  724. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  725. break;
  726. case 'info':
  727. await ctx.service.change.saveInfo(data.updateData);
  728. // 取所有工料表
  729. responseData.data = '保存成功';
  730. break;
  731. case 'paste_amount_rows':
  732. await ctx.service.changeAuditList.saveDatas(data.updateData);
  733. let changeList = await ctx.service.changeAuditList.getList(ctx.change.cid);
  734. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times);
  735. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  736. for (const cl of changeList) {
  737. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  738. // 清单表页赋值
  739. for (const [index, au] of auditList2.entries()) {
  740. if (au.usite !== 0) {
  741. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  742. }
  743. }
  744. }
  745. // 取所有工料表
  746. responseData.data = changeList;
  747. break;
  748. default: throw '参数有误';
  749. }
  750. ctx.body = responseData;
  751. } catch (err) {
  752. this.log(err);
  753. ctx.body = { err: 1, msg: err.toString(), data: null };
  754. }
  755. }
  756. /**
  757. * 上报和重新上报
  758. * @param ctx
  759. * @return {Promise<void>}
  760. */
  761. async startAudit(ctx) {
  762. try {
  763. // 检查权限等
  764. if (!ctx.change) {
  765. throw '数据错误';
  766. }
  767. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  768. throw '您无权上报该变更令数据';
  769. }
  770. if (!(ctx.change.status === audit.flow.status.uncheck || ctx.change.status === audit.flow.status.back || ctx.change.status === audit.flow.status.revise)) {
  771. throw '该变更令当前无法上报';
  772. }
  773. // 判断是否是修订,判断有无审批人员作弊
  774. if ((ctx.change.status === audit.flow.status.revise || ctx.change.is_revise) && ctx.tender.info.shenpi.change === shenpiConst.sp_status.sqspr) {
  775. // 获取上一次的审批人流程
  776. const lastUserList = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times - 1);
  777. const lastUidList = ctx.helper._.map(lastUserList, 'uid');
  778. // 判断上一次审批是否为非原报为审批人
  779. const nowUidList = ctx.helper._.map(ctx.change.auditors, 'uid');
  780. // 判断条件修订可上报条件
  781. // 1.有原报,有其他人 可以添加原报作为审核人,但是不能只原报上报
  782. // 2.有原报,无其他人 可以添加原报作为审核人,可以只原报上报
  783. // 3.无原报,有其他人 不可以添加原报
  784. const noYBUidList = ctx.change.status === audit.flow.status.revise ? ctx.helper._.initial(ctx.helper._.tail(lastUidList)) : ctx.helper._.tail(lastUidList);
  785. if (!ctx.helper._.isEqual(lastUidList, nowUidList) && ctx.helper._.includes(noYBUidList, lastUidList[0]) && nowUidList.length === 2 && nowUidList[0] === nowUidList[1]) {
  786. throw '该变更令不能指定原报人为单独审批人';
  787. }
  788. if (!ctx.helper._.isEqual(lastUidList, nowUidList) && !ctx.helper._.includes(noYBUidList, lastUidList[0]) && ctx.helper._.includes(ctx.helper._.tail(nowUidList), nowUidList[0])) {
  789. throw '该变更令不能指定原报为审批人,请移除';
  790. }
  791. }
  792. await ctx.service.changeAudit.start(ctx.change.cid, ctx.change.times);
  793. ctx.redirect(ctx.request.header.referer);
  794. } catch (err) {
  795. this.log(err);
  796. ctx.session.postError = err.toString();
  797. ctx.redirect(ctx.request.header.referer);
  798. }
  799. }
  800. // 审批相关
  801. /**
  802. * 添加审批人
  803. * @param ctx
  804. * @return {Promise<void>}
  805. */
  806. async addAudit(ctx) {
  807. try {
  808. const data = JSON.parse(ctx.request.body.data);
  809. const id = this.app._.toInteger(data.auditorId);
  810. if (isNaN(id) || id <= 0) {
  811. throw '参数错误';
  812. }
  813. // 检查权限等
  814. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  815. throw '您无权添加审核人';
  816. }
  817. if (ctx.change.status === audit.flow.status.checking || ctx.change.status === audit.flow.status.checked) {
  818. throw '当前不允许添加审核人';
  819. }
  820. const auditorList = await ctx.service.changeAudit.getAuditors(ctx.change.cid, ctx.change.times);
  821. // 检查审核人是否已存在
  822. const exist = this.app._.find(auditorList, { uid: id });
  823. if (exist) {
  824. throw '该审核人已存在,请勿重复添加';
  825. }
  826. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdzs });
  827. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs ? 1 : 0;
  828. const result = await ctx.service.changeAudit.addAuditor(ctx.change.cid, id, ctx.change.times, is_gdzs);
  829. if (!result) {
  830. throw '添加审核人失败';
  831. }
  832. // const auditors = await ctx.service.changeAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  833. const auditors = null;
  834. ctx.body = { err: 0, msg: '', data: auditors };
  835. } catch (err) {
  836. this.log(err);
  837. ctx.body = { err: 1, msg: err.toString(), data: null };
  838. }
  839. }
  840. /**
  841. * 移除审批人
  842. * @param ctx
  843. * @return {Promise<void>}
  844. */
  845. async deleteAudit(ctx) {
  846. try {
  847. const data = JSON.parse(ctx.request.body.data);
  848. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  849. if (isNaN(id) || id <= 0) {
  850. throw '参数错误';
  851. }
  852. const result = await ctx.service.changeAudit.deleteAuditor(ctx.change.cid, id, ctx.change.times);
  853. if (!result) {
  854. throw '移除审核人失败';
  855. }
  856. const auditors = null;
  857. ctx.body = { err: 0, msg: '', data: auditors };
  858. } catch (err) {
  859. ctx.body = { err: 1, msg: err.toString(), data: null };
  860. }
  861. }
  862. async defaultBills(ctx) {
  863. try {
  864. const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  865. const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  866. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  867. ctx.body = { err: 0, msg: '', data: { bills: ledgerData, pos: posData, dealBills } };
  868. } catch (err) {
  869. this.log(err);
  870. ctx.body = { err: 1, msg: err.toString(), data: [] };
  871. }
  872. }
  873. /**
  874. * 变更令上报和保存
  875. * @param {Object} ctx - egg全局变量
  876. * @return {void}
  877. */
  878. async save(ctx) {
  879. // 变更令信息
  880. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  881. try {
  882. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  883. if (!result) {
  884. throw '上报失败';
  885. }
  886. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  887. ctx.body = { err: 0, msg: '保存成功' };
  888. } else {
  889. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  890. }
  891. } catch (err) {
  892. this.log(err);
  893. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  894. ctx.body = { err: 1, msg: err.toString() };
  895. } else {
  896. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  897. }
  898. }
  899. }
  900. /**
  901. * 变更令审批
  902. * @param {Object} ctx - egg全局变量
  903. * @return {void}
  904. */
  905. async approval(ctx) {
  906. try {
  907. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.change_id });
  908. if (!changeData) {
  909. throw '变更令数据错误';
  910. }
  911. const status = parseInt(ctx.request.body.status);
  912. let result = false;
  913. const pid = this.ctx.session.sessionProject.id;
  914. switch (status) {
  915. case 3:// 审批通过
  916. result = await ctx.service.change.approvalSuccess(pid, ctx.request.body, changeData);
  917. break;
  918. case 4:// 审批终止
  919. result = await ctx.service.change.approvalStop(ctx.request.body);
  920. break;
  921. case 5:// 审批退回到原报人
  922. result = await ctx.service.change.approvalBack(pid, ctx.request.body, changeData);
  923. break;
  924. case 6:// 审批退回到上一个审批人
  925. result = await ctx.service.change.approvalBackNew(pid, ctx.request.body, changeData);
  926. break;
  927. default:break;
  928. }
  929. if (!result) {
  930. throw '审批失败';
  931. }
  932. ctx.redirect(ctx.request.header.referer);
  933. } catch (err) {
  934. console.log(err);
  935. ctx.redirect(ctx.request.header.referer);
  936. }
  937. }
  938. /**
  939. * 变更公司管理
  940. * @param {Object} ctx - egg全局变量
  941. * @return {void}
  942. */
  943. async updateCompany(ctx) {
  944. const responseData = {
  945. err: 0,
  946. msg: '',
  947. data: '',
  948. };
  949. try {
  950. const data = JSON.parse(ctx.request.body.data);
  951. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  952. throw '参数有误';
  953. }
  954. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  955. responseData.data = { add: addCompany, select: selectCompany };
  956. } catch (err) {
  957. responseData.err = 1;
  958. responseData.msg = err;
  959. }
  960. ctx.body = responseData;
  961. }
  962. /**
  963. * 上传附件
  964. * @param {Object} ctx - egg全局变量
  965. * @return {void}
  966. */
  967. async uploadFile(ctx) {
  968. const responseData = {
  969. err: 0,
  970. msg: '',
  971. data: [],
  972. };
  973. let stream;
  974. try {
  975. const parts = ctx.multipart({ autoFields: true });
  976. const files = [];
  977. let index = 0;
  978. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  979. const extra_upload = change.status === audit.flow.status.checked;
  980. while ((stream = await parts()) !== undefined) {
  981. // 判断用户是否选择上传文件
  982. if (!stream.filename) {
  983. throw '请选择上传的文件!';
  984. }
  985. // const create_time = Date.parse(new Date()) / 1000;
  986. // const fileInfo = path.parse(stream.filename);
  987. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  988. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  989. // // 判断文件夹是否存在,不存在则直接创建文件夹
  990. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  991. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  992. // }
  993. // // 保存文件
  994. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  995. const fileInfo = path.parse(stream.filename);
  996. const create_time = Date.parse(new Date()) / 1000;
  997. const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  998. await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  999. await sendToWormhole(stream);
  1000. // 保存数据到att表
  1001. const fileData = {
  1002. in_time: create_time,
  1003. filename: fileInfo.name,
  1004. fileext: fileInfo.ext,
  1005. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  1006. filepath,
  1007. extra_upload,
  1008. };
  1009. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  1010. if (!result) {
  1011. throw '导入数据库保存失败';
  1012. }
  1013. // fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  1014. // fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  1015. fileData.uid = ctx.session.sessionUser.accountId;
  1016. fileData.id = result.insertId;
  1017. delete fileData.filepath;
  1018. files.push(fileData);
  1019. ++index;
  1020. }
  1021. responseData.data = files;
  1022. } catch (err) {
  1023. this.log(err);
  1024. // 失败需要消耗掉stream 以防卡死
  1025. if (stream) {
  1026. await sendToWormhole(stream);
  1027. }
  1028. this.setMessage(err.toString(), this.messageType.ERROR);
  1029. }
  1030. ctx.body = responseData;
  1031. }
  1032. /**
  1033. * 下载附件
  1034. * @param {Object} ctx - egg全局变量
  1035. * @return {void}
  1036. */
  1037. async downloadFile(ctx) {
  1038. const id = ctx.params.id;
  1039. if (id) {
  1040. try {
  1041. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1042. if (fileInfo !== undefined && fileInfo !== '') {
  1043. const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  1044. // 解决中文无法下载问题
  1045. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1046. let disposition = '';
  1047. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1048. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  1049. } else if (userAgent.indexOf('firefox') >= 0) {
  1050. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  1051. } else {
  1052. /* safari等其他非主流浏览器只能自求多福了 */
  1053. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  1054. }
  1055. ctx.response.set({
  1056. 'Content-Type': 'application/octet-stream',
  1057. 'Content-Disposition': disposition,
  1058. 'Content-Length': fileInfo.filesize,
  1059. });
  1060. ctx.body = await fs.createReadStream(fileName);
  1061. } else {
  1062. throw '不存在该文件';
  1063. }
  1064. } catch (err) {
  1065. this.log(err);
  1066. this.setMessage(err.toString(), this.messageType.ERROR);
  1067. }
  1068. }
  1069. }
  1070. /**
  1071. * 批量下载 - 压缩成zip文件返回
  1072. * @param {Oject} ctx - 全局上下文
  1073. */
  1074. async downloadZip(ctx) {
  1075. try {
  1076. const fileIds = JSON.parse(ctx.request.query.fileIds);
  1077. // const { fileIds } = JSON.parse(ctx.request.body.data);
  1078. // console.log('fileIds', fileIds);
  1079. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  1080. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  1081. const time = Date.now();
  1082. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  1083. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  1084. // 解决中文无法下载问题
  1085. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1086. let disposition = '';
  1087. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1088. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  1089. } else if (userAgent.indexOf('firefox') >= 0) {
  1090. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  1091. } else {
  1092. /* safari等其他非主流浏览器只能自求多福了 */
  1093. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  1094. }
  1095. ctx.response.set({
  1096. 'Content-Type': 'application/octet-stream',
  1097. 'Content-Disposition': disposition,
  1098. 'Content-Length': size,
  1099. });
  1100. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  1101. ctx.body = readStream;
  1102. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  1103. readStream.on('close', () => {
  1104. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1105. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1106. }
  1107. });
  1108. } catch (error) {
  1109. this.log(error);
  1110. }
  1111. }
  1112. /**
  1113. * 删除附件
  1114. * @param {Object} ctx - egg全局变量
  1115. * @return {void}
  1116. */
  1117. async deleteFile(ctx) {
  1118. const responseData = {
  1119. err: 0,
  1120. msg: '',
  1121. data: '',
  1122. };
  1123. try {
  1124. const data = JSON.parse(ctx.request.body.data);
  1125. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1126. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  1127. if (!fileInfo || !Object.keys(fileInfo).length) {
  1128. throw '该文件不存在';
  1129. }
  1130. if (!fileInfo.extra_upload && change.status === audit.flow.status.checked) {
  1131. throw '无权限删除';
  1132. }
  1133. if (fileInfo !== undefined && fileInfo !== '') {
  1134. // 先删除文件
  1135. await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  1136. // 再删除数据库
  1137. await ctx.service.changeAtt.deleteById(data.id);
  1138. responseData.data = '';
  1139. } else {
  1140. throw '不存在该文件';
  1141. }
  1142. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1143. // throw '参数有误';
  1144. // }
  1145. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1146. // responseData.data = { add: addCompany, select: selectCompany };
  1147. } catch (err) {
  1148. responseData.err = 1;
  1149. responseData.msg = err;
  1150. }
  1151. ctx.body = responseData;
  1152. }
  1153. /**
  1154. * 查看附件
  1155. * @param {Object} ctx - egg全局变量
  1156. * @return {void}
  1157. */
  1158. async checkFile(ctx) {
  1159. const responseData = { err: 0, msg: '' };
  1160. const id = parseInt(ctx.params.id);
  1161. if (id) {
  1162. try {
  1163. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1164. if (fileInfo && Object.keys(fileInfo).length) {
  1165. let filepath = fileInfo.filepath;
  1166. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  1167. filepath = `/change/download/file/${fileInfo.id}`;
  1168. } else {
  1169. filepath = filepath.replace(/^app|\/app/, '');
  1170. }
  1171. fileInfo.filepath && (responseData.data = { filepath });
  1172. }
  1173. } catch (error) {
  1174. this.log(error);
  1175. this.setMessage(error.toString(), this.messageType.ERROR);
  1176. responseData.err = 1;
  1177. responseData.msg = error.toString();
  1178. }
  1179. }
  1180. ctx.body = responseData;
  1181. }
  1182. /**
  1183. * 删除变更令
  1184. * @param {Object} ctx - egg全局变量
  1185. * @return {void}
  1186. */
  1187. async delete(ctx) {
  1188. try {
  1189. const result = await ctx.service.change.delete(ctx.request.body.cid);
  1190. if (!result) {
  1191. throw '删除变更令失败';
  1192. }
  1193. ctx.redirect(ctx.request.header.referer);
  1194. } catch (err) {
  1195. console.log(err);
  1196. ctx.redirect(ctx.request.header.referer);
  1197. }
  1198. }
  1199. /**
  1200. * 变更令重新审批
  1201. * @param {Object} ctx - egg全局变量
  1202. * @return {void}
  1203. */
  1204. async checkAgain(ctx) {
  1205. try {
  1206. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1207. if (!changeData) {
  1208. throw '变更令数据错误';
  1209. }
  1210. // 获取终审
  1211. const auditInfo = (await this.ctx.service.changeAudit.getAllDataByCondition({ where: { cid: changeData.cid }, orders: [['usort', 'desc']], limit: 1, offset: 0 }))[0];
  1212. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== auditInfo.uid) {
  1213. throw '您无权进行该操作';
  1214. }
  1215. if (ctx.session.sessionUser.loginStatus === 0) {
  1216. const code = ctx.request.body.code;
  1217. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1218. if (!pa.auth_mobile) {
  1219. throw '未绑定手机号';
  1220. }
  1221. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1222. const cacheCode = await app.redis.get(cacheKey);
  1223. // console.log(cacheCode);
  1224. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1225. throw '验证码不正确!';
  1226. }
  1227. }
  1228. // 获取是否已存在调用变更令
  1229. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, changeData.cid);
  1230. const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  1231. if (stageChangeNum !== 0) {
  1232. throw '该变更令已被调用,无法重新审批';
  1233. }
  1234. // 重新审批
  1235. const result = await ctx.service.change.checkAgain(changeData.cid);
  1236. if (!result) {
  1237. throw '重新审批失败';
  1238. }
  1239. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1240. ctx.body = {
  1241. err: 0,
  1242. url: ctx.request.header.referer,
  1243. msg: '',
  1244. };
  1245. } catch (err) {
  1246. console.log(err);
  1247. // ctx.redirect(ctx.request.header.referer);
  1248. ctx.body = {
  1249. err: 1,
  1250. // url: ctx.request.header.referer,
  1251. msg: err,
  1252. };
  1253. }
  1254. }
  1255. /**
  1256. * 变更令修订重新上报
  1257. * @param {Object} ctx - egg全局变量
  1258. * @return {void}
  1259. */
  1260. async checkRevise(ctx) {
  1261. try {
  1262. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1263. if (!changeData) {
  1264. throw '变更令数据错误';
  1265. }
  1266. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== changeData.uid) {
  1267. throw '您无权进行该操作';
  1268. }
  1269. if (ctx.session.sessionUser.loginStatus === 0) {
  1270. const code = ctx.request.body.code;
  1271. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1272. if (!pa.auth_mobile) {
  1273. throw '未绑定手机号';
  1274. }
  1275. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1276. const cacheCode = await app.redis.get(cacheKey);
  1277. // console.log(cacheCode);
  1278. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1279. throw '验证码不正确!';
  1280. }
  1281. }
  1282. // 获取是否已存在调用变更令
  1283. // const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, changeData.cid);
  1284. // const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  1285. // if (stageChangeNum !== 0) {
  1286. // throw '该变更令已被调用,无法重新审批';
  1287. // }
  1288. // 重新审批
  1289. const result = await ctx.service.change.checkRevise(changeData.cid);
  1290. if (!result) {
  1291. throw '修订发起失败';
  1292. }
  1293. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1294. ctx.body = {
  1295. err: 0,
  1296. url: ctx.request.header.referer,
  1297. msg: '',
  1298. };
  1299. } catch (err) {
  1300. console.log(err);
  1301. // ctx.redirect(ctx.request.header.referer);
  1302. ctx.body = {
  1303. err: 1,
  1304. // url: ctx.request.header.referer,
  1305. msg: err,
  1306. };
  1307. }
  1308. }
  1309. /**
  1310. * 获取变更清单
  1311. * @param ctx
  1312. * @return {Promise<void>}
  1313. */
  1314. async bills(ctx) {
  1315. try {
  1316. const data = JSON.parse(ctx.request.body.data);
  1317. const responseData = { err: 0, msg: '', data: [] };
  1318. switch (data.type) {
  1319. case 'gather':
  1320. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  1321. break;
  1322. default:
  1323. throw '查询的数据不存在';
  1324. }
  1325. ctx.body = responseData;
  1326. } catch (err) {
  1327. this.log(err);
  1328. this.ajaxErrorBody(err, '获取变更清单失败');
  1329. }
  1330. }
  1331. /**
  1332. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  1333. * @param ctx
  1334. * @return {Promise<void>}
  1335. */
  1336. async checkCodeRepeat(ctx) {
  1337. const responseData = {
  1338. err: 0,
  1339. msg: '',
  1340. data: '',
  1341. };
  1342. try {
  1343. const tenderId = ctx.params.id;
  1344. const cid = ctx.params.cid;
  1345. const data = JSON.parse(ctx.request.body.data);
  1346. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  1347. if (result) {
  1348. throw '该变更令号(批复编号)已使用';
  1349. }
  1350. } catch (err) {
  1351. responseData.err = 1;
  1352. responseData.msg = err;
  1353. }
  1354. ctx.body = responseData;
  1355. }
  1356. /**
  1357. * 拷贝其他变更令
  1358. * @param {object} ctx - 全局上下文
  1359. */
  1360. async copyChange(ctx) {
  1361. const responseData = {
  1362. err: 0,
  1363. msg: '',
  1364. data: '',
  1365. };
  1366. try {
  1367. const cid = ctx.params.cid;
  1368. const copy_cid = JSON.parse(ctx.request.body.data);
  1369. const result = await ctx.service.change.handleCopyChange(cid, copy_cid);
  1370. if (!result) {
  1371. responseData.err = 1;
  1372. responseData.msg = '拷贝失败!';
  1373. }
  1374. } catch (error) {
  1375. responseData.err = 1;
  1376. responseData.msg = error;
  1377. }
  1378. ctx.body = responseData;
  1379. }
  1380. }
  1381. return ChangeController;
  1382. };