change_controller.js 70 KB

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