change_controller.js 69 KB

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