change_controller.js 65 KB

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