change_controller.js 69 KB

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