change_controller.js 84 KB

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