change_controller.js 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939
  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 data = JSON.parse(ctx.request.body.data);
  188. let cCodeRule;
  189. let cConnector;
  190. let changeCount = 0;
  191. if (data && data.type) {
  192. const c_code_rules = tenderData.c_code_rules !== null ? JSON.parse(tenderData.c_code_rules) : null;
  193. cCodeRule = c_code_rules && c_code_rules[data.type + '_rule'] ? c_code_rules[data.type + '_rule'] : [];
  194. cConnector = c_code_rules && c_code_rules[data.type + '_connector'] ? c_code_rules[data.type + '_connector'] : null;
  195. if (data.type === codeRuleConst.ruleField[codeRuleConst.ruleType.apply]) {
  196. changeCount = await ctx.service.changeApply.count({ tid: tenderId });
  197. } else {
  198. changeCount = await ctx.service.changeProject.count({ tid: tenderId, type: codeRuleConst.ruleType[data.type] });
  199. }
  200. } else {
  201. cCodeRule = tenderData.c_rule !== null ? JSON.parse(tenderData.c_rule) : [];
  202. cConnector = tenderData.c_connector;
  203. changeCount = await ctx.service.change.count({ tid: tenderId });
  204. }
  205. const code = [];
  206. for (const rule of cCodeRule) {
  207. switch (rule.rule_type) {
  208. case codeRuleConst.measure.ruleType.dealCode:
  209. code.push(ctx.tender.info.deal_info.dealCode);
  210. break;
  211. case codeRuleConst.measure.ruleType.tenderName:
  212. code.push(tenderData.name);
  213. break;
  214. case codeRuleConst.measure.ruleType.text:
  215. code.push(rule.text);
  216. break;
  217. case codeRuleConst.measure.ruleType.inDate:
  218. code.push(moment().format('YYYY'));
  219. break;
  220. case codeRuleConst.measure.ruleType.addNo:
  221. let s = '0000000000';
  222. const count = rule.start + changeCount;
  223. s = s + count;
  224. code.push(s.substr(s.length - rule.format));
  225. break;
  226. default: break;
  227. }
  228. }
  229. responseData.data = code.join(cConnector !== null && cConnector !== 3 ? codeRuleConst.measure.connectorString[cConnector] : '');
  230. } catch (err) {
  231. responseData.err = 1;
  232. responseData.msg = err;
  233. }
  234. ctx.body = responseData;
  235. }
  236. /**
  237. * 新增变更 (Post)
  238. *
  239. * @param {Object} ctx - egg全局变量
  240. * @return {void}
  241. */
  242. async add(ctx) {
  243. try {
  244. const tenderId = ctx.params.id;
  245. if (!tenderId) {
  246. throw '当前未打开标段';
  247. }
  248. const data = JSON.parse(ctx.request.body.data);
  249. if (!data.code || data.code === '' || !data.name || data.name === '') {
  250. throw '变更令号不能为空';
  251. }
  252. const change = await ctx.service.change.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  253. ctx.body = { err: 0, msg: '', data: change };
  254. } catch (err) {
  255. this.log(err);
  256. ctx.body = { err: 1, msg: err.toString() };
  257. }
  258. }
  259. /**
  260. * 变更管理 状态筛选 页面 (Get)
  261. * @param {Object} ctx - egg全局变量
  262. * @return {void}
  263. */
  264. async status(ctx) {
  265. try {
  266. const status = parseInt(ctx.params.status);
  267. await this._filterChanges(ctx, status);
  268. } catch (err) {
  269. this.logger.error(err);
  270. ctx.redirect('/tender/' + ctx.params.id + '/change');
  271. }
  272. }
  273. /**
  274. * 变更信息 页面 (Get)
  275. *
  276. * @param {Object} ctx - egg全局变量
  277. * @return {void}
  278. */
  279. async info(ctx) {
  280. try {
  281. const whiteList = this.ctx.app.config.multipart.whitelist;
  282. const tenderid = ctx.params.id !== undefined ? ctx.params.id : ctx.session.sessionUser.tenderId;
  283. ctx.session.sessionUser.tenderId = tenderid;
  284. const tender = await ctx.service.tender.getDataById(tenderid);
  285. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  286. // 后台判断当前人查看info状态
  287. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  288. // 获取附件列表
  289. const attList = await ctx.service.changeAtt.getChangeAttachment(ctx.params.cid);
  290. // 获取其他变更令数据
  291. const othersChange = await ctx.service.change.getOthersChange(ctx.params.id, ctx.params.cid);
  292. // 根据auditStatus获取审批人列表
  293. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  294. // 获取已选清单
  295. let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  296. // 获取用户人验证手机号
  297. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  298. const auth_mobile = pa.auth_mobile;
  299. const renderData = {
  300. uid: ctx.session.sessionUser.accountId,
  301. tender,
  302. change,
  303. othersChange,
  304. changeConst,
  305. auditStatus,
  306. auditConst: audit.flow,
  307. ledgerConsts: audit.ledger.status,
  308. attList,
  309. whiteList,
  310. auditList,
  311. changeList,
  312. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  313. upUnit: change.up_decimal ? change.up_decimal : ctx.tender.info.decimal.up,
  314. authMobile: auth_mobile,
  315. shenpiConst,
  316. };
  317. // 根据auditStatus状态获取的不同的数据
  318. if (auditStatus === 1 || auditStatus === 2 || auditStatus === 9) {
  319. renderData.changeUnits = changeConst.units;
  320. renderData.precision = ctx.tender.info.precision;
  321. // renderData.accountGroup = accountGroup;
  322. // 获取所有项目参与者
  323. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  324. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  325. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  326. });
  327. renderData.accountList = accountList;
  328. renderData.accountGroup = accountGroup.map((item, idx) => {
  329. const groupList = accountList.filter(item => item.account_group === idx);
  330. return { groupName: item, groupList };
  331. });
  332. // 重新上报获取审批流程
  333. if (auditStatus === 2 || auditStatus === 9) {
  334. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  335. // 展示页右侧审批流程列表
  336. const auditList3 = [];
  337. for (let time = 1; time <= change.times - 1; time++) {
  338. const auditTimeList = [];
  339. let max_sort = 1;
  340. for (const al of auditList2) {
  341. if (al.times === time) {
  342. auditTimeList.push(al);
  343. if (al.usite > max_sort) {
  344. max_sort = al.usite;
  345. }
  346. }
  347. }
  348. for (const i in auditTimeList) {
  349. auditTimeList[i].max_sort = max_sort;
  350. }
  351. auditList3.push(auditTimeList);
  352. }
  353. renderData.auditList3 = auditList3;
  354. }
  355. // 根据清单获取提交数据和计算总金额
  356. const changeListData = [];
  357. const changeWhiteListData = [];
  358. let ototalCost = 0;
  359. let ctotalCost = 0;
  360. for (const cl of changeList) {
  361. const cLArray = [
  362. cl.code,
  363. cl.name,
  364. cl.bwmx,
  365. cl.unit,
  366. cl.unit_price,
  367. cl.oamount,
  368. cl.camount,
  369. cl.detail,
  370. cl.lid,
  371. cl.xmj_code,
  372. cl.xmj_jldy,
  373. cl.gcl_id,
  374. ];
  375. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, ctx.tender.info.decimal.tp);
  376. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, ctx.tender.info.decimal.tp);
  377. if (cl.lid !== '0') {
  378. changeListData.push(cLArray.join('*;*'));
  379. } else {
  380. changeWhiteListData.push(cLArray.join('*;*'));
  381. }
  382. }
  383. renderData.changeListData = changeListData.join('^_^');
  384. renderData.changeWhiteListData = changeWhiteListData.join('^_^');
  385. renderData.ototalCost = ototalCost;
  386. renderData.ctotalCost = ctotalCost;
  387. // 获取公司列表
  388. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: tenderid } });
  389. renderData.companyList = companyList;
  390. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7) {
  391. // 展示页左侧审批流程列表和清单审批列表数据
  392. const times = change.status === audit.flow.status.back ?
  393. change.times - 1 : change.times;
  394. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  395. // 展示页右侧审批流程列表
  396. const auditList3 = [];
  397. for (let time = 1; time <= times; time++) {
  398. const auditTimeList = [];
  399. let max_sort = 1;
  400. for (const al of auditList) {
  401. if (al.times === time) {
  402. auditTimeList.push(al);
  403. if (al.usite > max_sort) {
  404. max_sort = al.usite;
  405. }
  406. }
  407. }
  408. for (const i in auditTimeList) {
  409. auditTimeList[i].max_sort = max_sort;
  410. }
  411. auditList3.push(auditTimeList);
  412. }
  413. renderData.auditList3 = auditList3;
  414. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  415. renderData.changeList = changeList;
  416. let ototalCost = 0;
  417. let ctotalCost = 0;
  418. let stotalCost = 0;
  419. const auditTotalCost = [];
  420. for (const cl of changeList) {
  421. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  422. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  423. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  424. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  425. // stotalCost += cl.samount !== '' && cl.unit_price !== null ? parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.samount), renderData.tpUnit)) : 0;
  426. stotalCost += cl.samount !== '' && cl.unit_price !== null ? ctx.helper.mul(cl.unit_price, cl.samount, renderData.tpUnit) : 0;
  427. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  428. auditTotalCost.push(audit_amount);
  429. }
  430. renderData.ototalCost = ototalCost;
  431. renderData.ctotalCost = ctotalCost;
  432. renderData.stotalCost = stotalCost;
  433. // 清单表页赋值
  434. for (const [index, au] of auditList2.entries()) {
  435. if (au.usite !== 0) {
  436. au.list_amount = [];
  437. au.totalCost = 0;
  438. for (const [auindex, at] of auditTotalCost.entries()) {
  439. au.list_amount.push(at[index - 1]);
  440. // 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;
  441. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  442. }
  443. }
  444. }
  445. renderData.auditList2 = auditList2;
  446. } else if (auditStatus === 6) {
  447. // 展示页左侧审批流程列表和清单审批列表数据
  448. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  449. renderData.auditList2 = auditList2;
  450. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  451. for (const i in auditList3) {
  452. auditList3[i].max_sort = auditList2.length - 1;
  453. }
  454. renderData.auditList3 = auditList3;
  455. // 展示页右侧审批流程列表
  456. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  457. const auditList4 = [];
  458. for (let time = 1; time <= change.times; time++) {
  459. const auditTimeList = [];
  460. let max_sort = 1;
  461. for (const al of auditList5) {
  462. if (al.times === time) {
  463. auditTimeList.push(al);
  464. if (al.usite > max_sort) {
  465. max_sort = al.usite;
  466. }
  467. }
  468. }
  469. for (const i in auditTimeList) {
  470. auditTimeList[i].max_sort = max_sort;
  471. }
  472. if (auditTimeList.length > 0) {
  473. auditList4.push(auditTimeList);
  474. }
  475. }
  476. renderData.auditList4 = auditList4;
  477. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  478. renderData.changeList = changeList;
  479. let ototalCost = 0;
  480. let ctotalCost = 0;
  481. const auditTotalCost = [];
  482. const auditUnit = [];
  483. for (const cl of changeList) {
  484. // ototalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.oamount), renderData.tpUnit));
  485. ototalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.oamount, renderData.tpUnit);
  486. // ctotalCost += cl.unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(cl.unit_price, cl.camount), renderData.tpUnit));
  487. ctotalCost += cl.unit_price === null ? 0 : ctx.helper.mul(cl.unit_price, cl.camount, renderData.tpUnit);
  488. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  489. auditTotalCost.push(audit_amount);
  490. }
  491. renderData.ototalCost = ototalCost;
  492. renderData.ctotalCost = ctotalCost;
  493. // 清单表页赋值
  494. for (const [index, au] of auditList.entries()) {
  495. if (au.usite !== 0) {
  496. au.list_amount = [];
  497. au.totalCost = 0;
  498. if (au.uid === renderData.uid) {
  499. for (const [auindex, at] of auditTotalCost.entries()) {
  500. // if (at[index - 2] !== undefined) {
  501. // au.list_amount.push(at[index - 2]);
  502. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, at[index - 2]), renderData.tpUnit));
  503. // } else if (at[index - 2] === undefined) {
  504. // au.list_amount.push(changeList[auindex].camount);
  505. // au.totalCost += parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].camount), renderData.tpUnit));
  506. // }
  507. au.list_amount.push(changeList[auindex].spamount);
  508. // au.totalCost += changeList[auindex].unit_price === null ? 0 : parseFloat(ctx.helper.roundNum(ctx.helper.accMul(changeList[auindex].unit_price, changeList[auindex].spamount), renderData.tpUnit));
  509. au.totalCost += changeList[auindex].unit_price === null ? 0 : ctx.helper.mul(changeList[auindex].unit_price, changeList[auindex].spamount, renderData.tpUnit);
  510. }
  511. } else {
  512. for (const [auindex, at] of auditTotalCost.entries()) {
  513. au.list_amount.push(at[index - 1]);
  514. // 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;
  515. au.totalCost += at[index - 1] !== undefined && changeList[auindex].unit_price !== null ? ctx.helper.mul(changeList[auindex].unit_price, at[index - 1], renderData.tpUnit) : 0;
  516. }
  517. }
  518. }
  519. }
  520. }
  521. renderData.auditList = auditList;
  522. // 获取是否已存在调用变更令
  523. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  524. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  525. await this.layout('change/info.ejs', renderData, 'change/info_modal.ejs');
  526. } catch (err) {
  527. this.log(err);
  528. ctx.redirect('/tender/' + ctx.params.id + '/change');
  529. }
  530. }
  531. /**
  532. * 变更信息 新版本页面 (Get)
  533. *
  534. * @param {Object} ctx - egg全局变量
  535. * @return {void}
  536. */
  537. async information(ctx) {
  538. try {
  539. const whiteList = this.ctx.app.config.multipart.whitelist;
  540. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  541. const change = ctx.change;
  542. // 后台判断当前人查看info状态
  543. const auditStatus = await ctx.service.changeAudit.getStatusByChange(change);
  544. // 获取附件列表
  545. const attList = await ctx.service.changeAtt.getChangeAttachment(change.cid, 'desc');
  546. // 获取其他变更令数据
  547. const othersChange = await ctx.service.change.getOthersChange(ctx.tender.id, change.cid);
  548. // 根据auditStatus获取审批人列表
  549. const auditList = await ctx.service.changeAudit.getListByStatus(change, auditStatus);
  550. // 获取用户人验证手机号
  551. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  552. const auth_mobile = pa.auth_mobile;
  553. const renderData = {
  554. tender,
  555. change,
  556. othersChange,
  557. changeConst,
  558. auditStatus,
  559. auditConst: audit.flow,
  560. ledgerConsts: audit.ledger.status,
  561. attList,
  562. whiteList,
  563. auditList,
  564. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  565. upUnit: change.up_decimal ? change.up_decimal : ctx.tender.info.decimal.up,
  566. authMobile: auth_mobile,
  567. shenpiConst,
  568. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.information),
  569. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  570. precision: ctx.tender.info.precision,
  571. };
  572. // 根据auditStatus状态获取的不同的数据
  573. if (auditStatus === 1 || auditStatus === 2 || auditStatus === 9) {
  574. renderData.changeUnits = changeConst.units;
  575. // renderData.accountGroup = accountGroup;
  576. // 获取所有项目参与者
  577. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  578. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  579. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group'],
  580. });
  581. renderData.accountList = accountList;
  582. renderData.accountGroup = accountGroup.map((item, idx) => {
  583. const groupList = accountList.filter(item => item.account_group === idx);
  584. return { groupName: item, groupList };
  585. });
  586. // 重新上报获取审批流程
  587. if (auditStatus === 2 || auditStatus === 9) {
  588. const auditList2 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  589. // 展示页右侧审批流程列表
  590. const auditList3 = [];
  591. for (let time = 1; time <= change.times - 1; time++) {
  592. const auditTimeList = [];
  593. let max_sort = 1;
  594. for (const al of auditList2) {
  595. if (al.times === time) {
  596. auditTimeList.push(al);
  597. if (al.usite > max_sort) {
  598. max_sort = al.usite;
  599. }
  600. }
  601. }
  602. for (const i in auditTimeList) {
  603. auditTimeList[i].max_sort = max_sort;
  604. }
  605. auditList3.push(auditTimeList);
  606. }
  607. renderData.auditList3 = auditList3;
  608. }
  609. // 获取公司列表
  610. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  611. renderData.companyList = companyList;
  612. // 获取已选清单
  613. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  614. renderData.changeList = changeList;
  615. renderData.changeLedgerList = await ctx.service.changeLedger.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  616. renderData.changePosList = await ctx.service.changePos.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  617. } else if (auditStatus === 3 || auditStatus === 4 || auditStatus === 5 || auditStatus === 7 || auditStatus === 8) {
  618. // 展示页左侧审批流程列表和清单审批列表数据
  619. const times = change.status === audit.flow.status.back ?
  620. change.times - 1 : change.times;
  621. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, times);
  622. // 展示页右侧审批流程列表
  623. const auditList3 = [];
  624. for (let time = 1; time <= times; time++) {
  625. const auditTimeList = [];
  626. let max_sort = 1;
  627. for (const al of auditList) {
  628. if (al.times === time) {
  629. auditTimeList.push(al);
  630. if (al.usite > max_sort) {
  631. max_sort = al.usite;
  632. }
  633. }
  634. }
  635. for (const i in auditTimeList) {
  636. auditTimeList[i].max_sort = max_sort;
  637. }
  638. auditList3.push(auditTimeList);
  639. }
  640. renderData.auditList3 = auditList3;
  641. // 获取已选清单
  642. // let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  643. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  644. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  645. for (const cl of changeList) {
  646. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  647. // 清单表页赋值
  648. for (const [index, au] of auditList2.entries()) {
  649. if (au.usite !== 0) {
  650. cl['audit_amount_' + au.uid] = audit_amount[index - 1] ? audit_amount[index - 1] : null;
  651. }
  652. }
  653. }
  654. renderData.changeList = changeList;
  655. renderData.auditList2 = auditList2;
  656. } else if (auditStatus === 6) {
  657. // 展示页左侧审批流程列表和清单审批列表数据
  658. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(change.cid, change.times);
  659. renderData.auditList2 = auditList2;
  660. const auditList3 = await ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  661. for (const i in auditList3) {
  662. auditList3[i].max_sort = auditList2.length - 1;
  663. }
  664. renderData.auditList3 = auditList3;
  665. // 展示页右侧审批流程列表
  666. const auditList5 = await ctx.service.changeAudit.getListByBack(change.cid, change.times);
  667. const auditList4 = [];
  668. for (let time = 1; time <= change.times; time++) {
  669. const auditTimeList = [];
  670. let max_sort = 1;
  671. for (const al of auditList5) {
  672. if (al.times === time) {
  673. auditTimeList.push(al);
  674. if (al.usite > max_sort) {
  675. max_sort = al.usite;
  676. }
  677. }
  678. }
  679. for (const i in auditTimeList) {
  680. auditTimeList[i].max_sort = max_sort;
  681. }
  682. if (auditTimeList.length > 0) {
  683. auditList4.push(auditTimeList);
  684. }
  685. }
  686. renderData.auditList4 = auditList4;
  687. // 获取已选清单
  688. // let changeList = await ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: ctx.params.cid } });
  689. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  690. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  691. for (const cl of changeList) {
  692. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  693. // 清单表页赋值
  694. for (const [index, au] of auditList2.entries()) {
  695. if (au.usite !== 0) {
  696. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  697. }
  698. }
  699. }
  700. renderData.changeList = changeList;
  701. renderData.changeLedgerList = await ctx.service.changeLedger.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  702. renderData.changePosList = await ctx.service.changePos.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  703. }
  704. renderData.auditList = auditList;
  705. // 获取是否已存在调用变更令
  706. let changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, change.cid);
  707. changeUsedData = ctx.helper._.filter(changeUsedData, function(item) {
  708. return item.used_qty !== null;
  709. })
  710. renderData.changeUsedData = changeUsedData;
  711. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  712. await this.layout('change/information.ejs', renderData, 'change/information_modal.ejs');
  713. } catch (err) {
  714. this.log(err);
  715. ctx.redirect('/tender/' + ctx.params.id + '/change');
  716. }
  717. }
  718. /**
  719. * 变更清单 - 操作 (Ajax)
  720. * @param ctx
  721. * @return {Promise<void>}
  722. */
  723. async saveListsData(ctx) {
  724. try {
  725. const data = JSON.parse(ctx.request.body.data);
  726. const responseData = {
  727. err: 0,
  728. msg: '',
  729. data: {},
  730. };
  731. switch (data.type) {
  732. case 'add':
  733. responseData.data = await ctx.service.changeAuditList.add(data.postData);
  734. break;
  735. case 'batchadd':
  736. responseData.data = await ctx.service.changeAuditList.batchAdd(data);
  737. break;
  738. case 'del':
  739. await ctx.service.changeAuditList.del(data.id);
  740. break;
  741. case 'update':
  742. await ctx.service.changeAuditList.save(data.updateData);
  743. break;
  744. case 'paste':
  745. await ctx.service.changeAuditList.saveDatas(data.updateData);
  746. // 取所有工料表
  747. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  748. break;
  749. case 'ledger_list':
  750. await ctx.service.changeAuditList.saveLedgerListDatas(data.updateData);
  751. // 取所有工料表
  752. responseData.data = { changeList: await ctx.service.changeAuditList.getList(ctx.change.cid),
  753. usedList: await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, ctx.change.cid) };
  754. break;
  755. case 'remove_list':
  756. await ctx.service.changeAuditList.removeLedgerListDatas(data.updateData);
  757. // 取所有工料表
  758. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  759. break;
  760. case 'update_list':
  761. await ctx.service.changeAuditList.saveDatas(data.updateData);
  762. // 取所有工料表
  763. // responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  764. break;
  765. case 'info':
  766. await ctx.service.change.saveInfo(data.updateData);
  767. // 取所有工料表
  768. responseData.data = '保存成功';
  769. break;
  770. case 'paste_amount_rows':
  771. await ctx.service.changeAuditList.saveDatas(data.updateData);
  772. let changeList = await ctx.service.changeAuditList.getList(ctx.change.cid);
  773. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times);
  774. changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  775. for (const cl of changeList) {
  776. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  777. // 清单表页赋值
  778. for (const [index, au] of auditList2.entries()) {
  779. if (au.usite !== 0) {
  780. cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  781. }
  782. }
  783. }
  784. // 取所有工料表
  785. responseData.data = changeList;
  786. break;
  787. default: throw '参数有误';
  788. }
  789. ctx.body = responseData;
  790. } catch (err) {
  791. this.log(err);
  792. ctx.body = { err: 1, msg: err.toString(), data: null };
  793. }
  794. }
  795. /**
  796. * 上报和重新上报
  797. * @param ctx
  798. * @return {Promise<void>}
  799. */
  800. async startAudit(ctx) {
  801. try {
  802. // 检查权限等
  803. if (!ctx.change) {
  804. throw '数据错误';
  805. }
  806. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  807. throw '您无权上报该变更令数据';
  808. }
  809. if (!(ctx.change.status === audit.flow.status.uncheck || ctx.change.status === audit.flow.status.back || ctx.change.status === audit.flow.status.revise)) {
  810. throw '该变更令当前无法上报';
  811. }
  812. // 判断是否是修订,判断有无审批人员作弊
  813. if ((ctx.change.status === audit.flow.status.revise || ctx.change.is_revise) && ctx.tender.info.shenpi.change === shenpiConst.sp_status.sqspr) {
  814. // 获取上一次的审批人流程
  815. const lastUserList = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times - 1);
  816. const lastUidList = ctx.helper._.map(lastUserList, 'uid');
  817. // 判断上一次审批是否为非原报为审批人
  818. const nowUidList = ctx.helper._.map(ctx.change.auditors, 'uid');
  819. // 判断条件修订可上报条件
  820. // 1.有原报,有其他人 可以添加原报作为审核人,但是不能只原报上报
  821. // 2.有原报,无其他人 可以添加原报作为审核人,可以只原报上报
  822. // 3.无原报,有其他人 不可以添加原报
  823. const noYBUidList = ctx.change.status === audit.flow.status.revise ? ctx.helper._.initial(ctx.helper._.tail(lastUidList)) : ctx.helper._.tail(lastUidList);
  824. if (!ctx.helper._.isEqual(lastUidList, nowUidList) && ctx.helper._.includes(noYBUidList, lastUidList[0]) && nowUidList.length === 2 && nowUidList[0] === nowUidList[1]) {
  825. throw '该变更令不能指定原报人为单独审批人';
  826. }
  827. if (!ctx.helper._.isEqual(lastUidList, nowUidList) && !ctx.helper._.includes(noYBUidList, lastUidList[0]) && ctx.helper._.includes(ctx.helper._.tail(nowUidList), nowUidList[0])) {
  828. throw '该变更令不能指定原报为审批人,请移除';
  829. }
  830. }
  831. await ctx.service.changeAudit.start(ctx.change.cid, ctx.change.times);
  832. ctx.redirect(ctx.request.header.referer);
  833. } catch (err) {
  834. this.log(err);
  835. ctx.session.postError = err.toString();
  836. ctx.redirect(ctx.request.header.referer);
  837. }
  838. }
  839. // 审批相关
  840. /**
  841. * 添加审批人
  842. * @param ctx
  843. * @return {Promise<void>}
  844. */
  845. async addAudit(ctx) {
  846. try {
  847. const data = JSON.parse(ctx.request.body.data);
  848. const id = this.app._.toInteger(data.auditorId);
  849. if (isNaN(id) || id <= 0) {
  850. throw '参数错误';
  851. }
  852. // 检查权限等
  853. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  854. throw '您无权添加审核人';
  855. }
  856. if (ctx.change.status === audit.flow.status.checking || ctx.change.status === audit.flow.status.checked) {
  857. throw '当前不允许添加审核人';
  858. }
  859. const auditorList = await ctx.service.changeAudit.getAuditors(ctx.change.cid, ctx.change.times);
  860. // 检查审核人是否已存在
  861. const exist = this.app._.find(auditorList, { uid: id });
  862. if (exist) {
  863. throw '该审核人已存在,请勿重复添加';
  864. }
  865. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdzs });
  866. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs ? 1 : 0;
  867. const result = await ctx.service.changeAudit.addAuditor(ctx.change.cid, id, ctx.change.times, is_gdzs);
  868. if (!result) {
  869. throw '添加审核人失败';
  870. }
  871. // const auditors = await ctx.service.changeAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  872. const auditors = null;
  873. ctx.body = { err: 0, msg: '', data: auditors };
  874. } catch (err) {
  875. this.log(err);
  876. ctx.body = { err: 1, msg: err.toString(), data: null };
  877. }
  878. }
  879. /**
  880. * 移除审批人
  881. * @param ctx
  882. * @return {Promise<void>}
  883. */
  884. async deleteAudit(ctx) {
  885. try {
  886. const data = JSON.parse(ctx.request.body.data);
  887. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  888. if (isNaN(id) || id <= 0) {
  889. throw '参数错误';
  890. }
  891. const result = await ctx.service.changeAudit.deleteAuditor(ctx.change.cid, id, ctx.change.times);
  892. if (!result) {
  893. throw '移除审核人失败';
  894. }
  895. const auditors = null;
  896. ctx.body = { err: 0, msg: '', data: auditors };
  897. } catch (err) {
  898. ctx.body = { err: 1, msg: err.toString(), data: null };
  899. }
  900. }
  901. async defaultBills(ctx) {
  902. try {
  903. // 判断是否台账修订中,修订中则不获取changeLedger及changePos值
  904. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  905. const data = JSON.parse(ctx.request.body.data);
  906. const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  907. const changeLedgerData = !ctx.session.sessionProject.page_show.openChangeRevise ? [] : (lastRevise && lastRevise.status !== audit.revise.status.checked && data.from !== 'revise' ? [] : await ctx.service.changeLedger.getData(ctx.tender.id));
  908. const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  909. const changePosData = !ctx.session.sessionProject.page_show.openChangeRevise ? [] : (lastRevise && lastRevise.status !== audit.revise.status.checked && data.from !== 'revise' ? [] : await ctx.service.changePos.getPosData({ tid: ctx.tender.id }));
  910. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  911. // 标记ledger,搜索需求
  912. if (changePosData.length > 0) {
  913. const cplIdList = ctx.helper._.uniq(ctx.helper._.map(changePosData, 'lid'));
  914. const cLIdList = ctx.helper._.map(changeLedgerData, 'id');
  915. const ledgerIdList = [];
  916. for (const cp of cplIdList) {
  917. if (ctx.helper._.indexOf(cLIdList, cp) === -1) {
  918. ledgerIdList.push(cp);
  919. }
  920. }
  921. if (ledgerIdList.length > 0) {
  922. for (const lid of ledgerIdList) {
  923. const data = ctx.helper._.find(ledgerData, { id: lid });
  924. data.cid = 1;
  925. }
  926. }
  927. }
  928. ctx.body = { err: 0, msg: '', data: { bills: ctx.helper._.concat(ledgerData, changeLedgerData), pos: ctx.helper._.concat(posData, changePosData), dealBills } };
  929. } catch (err) {
  930. this.log(err);
  931. ctx.body = { err: 1, msg: err.toString(), data: [] };
  932. }
  933. }
  934. /**
  935. * 变更令上报和保存
  936. * @param {Object} ctx - egg全局变量
  937. * @return {void}
  938. */
  939. async save(ctx) {
  940. // 变更令信息
  941. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  942. try {
  943. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  944. if (!result) {
  945. throw '上报失败';
  946. }
  947. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  948. ctx.body = { err: 0, msg: '保存成功' };
  949. } else {
  950. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  951. }
  952. } catch (err) {
  953. this.log(err);
  954. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  955. ctx.body = { err: 1, msg: err.toString() };
  956. } else {
  957. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  958. }
  959. }
  960. }
  961. /**
  962. * 变更令审批
  963. * @param {Object} ctx - egg全局变量
  964. * @return {void}
  965. */
  966. async approval(ctx) {
  967. try {
  968. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.change_id });
  969. if (!changeData) {
  970. throw '变更令数据错误';
  971. }
  972. const status = parseInt(ctx.request.body.status);
  973. let result = false;
  974. const pid = this.ctx.session.sessionProject.id;
  975. switch (status) {
  976. case 3:// 审批通过
  977. result = await ctx.service.change.approvalSuccess(pid, ctx.request.body, changeData);
  978. break;
  979. case 4:// 审批终止
  980. result = await ctx.service.change.approvalStop(ctx.request.body);
  981. break;
  982. case 5:// 审批退回到原报人
  983. result = await ctx.service.change.approvalBack(pid, ctx.request.body, changeData);
  984. break;
  985. case 6:// 审批退回到上一个审批人
  986. result = await ctx.service.change.approvalBackNew(pid, ctx.request.body, changeData);
  987. break;
  988. default:break;
  989. }
  990. if (!result) {
  991. throw '审批失败';
  992. }
  993. ctx.redirect(ctx.request.header.referer);
  994. } catch (err) {
  995. console.log(err);
  996. ctx.redirect(ctx.request.header.referer);
  997. }
  998. }
  999. /**
  1000. * 变更公司管理
  1001. * @param {Object} ctx - egg全局变量
  1002. * @return {void}
  1003. */
  1004. async updateCompany(ctx) {
  1005. const responseData = {
  1006. err: 0,
  1007. msg: '',
  1008. data: '',
  1009. };
  1010. try {
  1011. const data = JSON.parse(ctx.request.body.data);
  1012. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1013. throw '参数有误';
  1014. }
  1015. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1016. responseData.data = { add: addCompany, select: selectCompany };
  1017. } catch (err) {
  1018. responseData.err = 1;
  1019. responseData.msg = err;
  1020. }
  1021. ctx.body = responseData;
  1022. }
  1023. /**
  1024. * 上传附件
  1025. * @param {Object} ctx - egg全局变量
  1026. * @return {void}
  1027. */
  1028. async uploadFile(ctx) {
  1029. const responseData = {
  1030. err: 0,
  1031. msg: '',
  1032. data: [],
  1033. };
  1034. let stream;
  1035. try {
  1036. const parts = ctx.multipart({ autoFields: true });
  1037. const files = [];
  1038. let index = 0;
  1039. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1040. const extra_upload = change.status === audit.flow.status.checked;
  1041. while ((stream = await parts()) !== undefined) {
  1042. // 判断用户是否选择上传文件
  1043. if (!stream.filename) {
  1044. throw '请选择上传的文件!';
  1045. }
  1046. // const create_time = Date.parse(new Date()) / 1000;
  1047. // const fileInfo = path.parse(stream.filename);
  1048. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  1049. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  1050. // // 判断文件夹是否存在,不存在则直接创建文件夹
  1051. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  1052. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  1053. // }
  1054. // // 保存文件
  1055. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  1056. const fileInfo = path.parse(stream.filename);
  1057. const create_time = Date.parse(new Date()) / 1000;
  1058. // const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  1059. const filepath = `app/public/upload/${parts.field.tid}/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  1060. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  1061. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  1062. await sendToWormhole(stream);
  1063. // 保存数据到att表
  1064. const fileData = {
  1065. in_time: create_time,
  1066. filename: fileInfo.name,
  1067. fileext: fileInfo.ext,
  1068. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  1069. filepath,
  1070. extra_upload,
  1071. };
  1072. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  1073. if (!result) {
  1074. throw '导入数据库保存失败';
  1075. }
  1076. // fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  1077. // fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  1078. fileData.uid = ctx.session.sessionUser.accountId;
  1079. fileData.id = result.insertId;
  1080. fileData.orginpath = ctx.app.config.fujianOssPath + filepath;
  1081. delete fileData.filepath;
  1082. files.push(fileData);
  1083. ++index;
  1084. }
  1085. responseData.data = files;
  1086. } catch (err) {
  1087. this.log(err);
  1088. // 失败需要消耗掉stream 以防卡死
  1089. if (stream) {
  1090. await sendToWormhole(stream);
  1091. }
  1092. this.setMessage(err.toString(), this.messageType.ERROR);
  1093. }
  1094. ctx.body = responseData;
  1095. }
  1096. /**
  1097. * 下载附件
  1098. * @param {Object} ctx - egg全局变量
  1099. * @return {void}
  1100. */
  1101. async downloadFile(ctx) {
  1102. const id = ctx.params.id;
  1103. if (id) {
  1104. try {
  1105. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1106. if (fileInfo !== undefined && fileInfo !== '') {
  1107. // const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  1108. // 解决中文无法下载问题
  1109. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1110. let disposition = '';
  1111. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1112. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  1113. } else if (userAgent.indexOf('firefox') >= 0) {
  1114. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  1115. } else {
  1116. /* safari等其他非主流浏览器只能自求多福了 */
  1117. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  1118. }
  1119. ctx.response.set({
  1120. 'Content-Type': 'application/octet-stream',
  1121. 'Content-Disposition': disposition,
  1122. 'Content-Length': fileInfo.filesize,
  1123. });
  1124. // ctx.body = await fs.createReadStream(fileName);
  1125. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  1126. } else {
  1127. throw '不存在该文件';
  1128. }
  1129. } catch (err) {
  1130. this.log(err);
  1131. this.setMessage(err.toString(), this.messageType.ERROR);
  1132. }
  1133. }
  1134. }
  1135. /**
  1136. * 批量下载 - 压缩成zip文件返回
  1137. * @param {Oject} ctx - 全局上下文
  1138. */
  1139. async downloadZip(ctx) {
  1140. const time = Date.now();
  1141. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  1142. const responseData = {
  1143. err: 0,
  1144. msg: '',
  1145. };
  1146. try {
  1147. // const fileIds = JSON.parse(ctx.request.query.fileIds);
  1148. const { fileIds = [] } = JSON.parse(ctx.request.body.data);
  1149. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  1150. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  1151. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  1152. // 解决中文无法下载问题
  1153. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1154. let disposition = '';
  1155. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1156. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  1157. } else if (userAgent.indexOf('firefox') >= 0) {
  1158. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  1159. } else {
  1160. /* safari等其他非主流浏览器只能自求多福了 */
  1161. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  1162. }
  1163. ctx.response.set({
  1164. 'Content-Type': 'application/octet-stream',
  1165. 'Content-Disposition': disposition,
  1166. 'Content-Length': size,
  1167. });
  1168. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  1169. ctx.body = readStream;
  1170. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  1171. readStream.on('close', () => {
  1172. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1173. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1174. }
  1175. });
  1176. // fs的错误不能被try catch捕捉
  1177. readStream.on('error', err => {
  1178. this.log(err);
  1179. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1180. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1181. }
  1182. responseData.err = 1;
  1183. responseData.msg = err.toString();
  1184. ctx.body = responseData;
  1185. });
  1186. } catch (err) {
  1187. this.log(err);
  1188. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1189. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1190. }
  1191. this.setMessage(err.toString(), this.messageType.ERROR);
  1192. responseData.err = 1;
  1193. responseData.msg = err.toString();
  1194. ctx.body = responseData;
  1195. }
  1196. }
  1197. /**
  1198. * 删除附件
  1199. * @param {Object} ctx - egg全局变量
  1200. * @return {void}
  1201. */
  1202. async deleteFile(ctx) {
  1203. const responseData = {
  1204. err: 0,
  1205. msg: '',
  1206. data: '',
  1207. };
  1208. try {
  1209. const data = JSON.parse(ctx.request.body.data);
  1210. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1211. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  1212. if (!fileInfo || !Object.keys(fileInfo).length) {
  1213. throw '该文件不存在';
  1214. }
  1215. if (!fileInfo.extra_upload && change.status === audit.flow.status.checked) {
  1216. throw '无权限删除';
  1217. }
  1218. if (fileInfo !== undefined && fileInfo !== '') {
  1219. // 先删除文件
  1220. // await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  1221. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  1222. // 再删除数据库
  1223. await ctx.service.changeAtt.deleteById(data.id);
  1224. responseData.data = '';
  1225. } else {
  1226. throw '不存在该文件';
  1227. }
  1228. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1229. // throw '参数有误';
  1230. // }
  1231. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1232. // responseData.data = { add: addCompany, select: selectCompany };
  1233. } catch (err) {
  1234. responseData.err = 1;
  1235. responseData.msg = err;
  1236. }
  1237. ctx.body = responseData;
  1238. }
  1239. /**
  1240. * 查看附件
  1241. * @param {Object} ctx - egg全局变量
  1242. * @return {void}
  1243. */
  1244. async checkFile(ctx) {
  1245. const responseData = { err: 0, msg: '' };
  1246. const id = parseInt(ctx.params.id);
  1247. if (id) {
  1248. try {
  1249. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1250. if (fileInfo && Object.keys(fileInfo).length) {
  1251. let filepath = fileInfo.filepath;
  1252. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  1253. filepath = `/change/download/file/${fileInfo.id}`;
  1254. } else {
  1255. filepath = filepath.replace(/^app|\/app/, '');
  1256. }
  1257. fileInfo.filepath && (responseData.data = { filepath });
  1258. }
  1259. } catch (error) {
  1260. this.log(error);
  1261. this.setMessage(error.toString(), this.messageType.ERROR);
  1262. responseData.err = 1;
  1263. responseData.msg = error.toString();
  1264. }
  1265. }
  1266. ctx.body = responseData;
  1267. }
  1268. /**
  1269. * 删除变更令
  1270. * @param {Object} ctx - egg全局变量
  1271. * @return {void}
  1272. */
  1273. async delete(ctx) {
  1274. try {
  1275. const result = await ctx.service.change.delete(ctx.request.body.cid);
  1276. if (!result) {
  1277. throw '删除变更令失败';
  1278. }
  1279. ctx.redirect(ctx.request.header.referer);
  1280. } catch (err) {
  1281. console.log(err);
  1282. ctx.redirect(ctx.request.header.referer);
  1283. }
  1284. }
  1285. /**
  1286. * 变更令重新审批
  1287. * @param {Object} ctx - egg全局变量
  1288. * @return {void}
  1289. */
  1290. async checkAgain(ctx) {
  1291. try {
  1292. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1293. if (!changeData) {
  1294. throw '变更令数据错误';
  1295. }
  1296. // 获取终审
  1297. const auditInfo = (await this.ctx.service.changeAudit.getAllDataByCondition({ where: { cid: changeData.cid }, orders: [['usort', 'desc']], limit: 1, offset: 0 }))[0];
  1298. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== auditInfo.uid) {
  1299. throw '您无权进行该操作';
  1300. }
  1301. if (ctx.session.sessionUser.loginStatus === 0) {
  1302. const code = ctx.request.body.code;
  1303. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1304. if (!pa.auth_mobile) {
  1305. throw '未绑定手机号';
  1306. }
  1307. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1308. const cacheCode = await app.redis.get(cacheKey);
  1309. // console.log(cacheCode);
  1310. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1311. throw '验证码不正确!';
  1312. }
  1313. }
  1314. // 获取是否已存在调用变更令
  1315. const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, changeData.cid);
  1316. const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  1317. if (stageChangeNum !== 0) {
  1318. throw '该变更令已被调用,无法重新审批';
  1319. }
  1320. // 重新审批
  1321. const result = await ctx.service.change.checkAgain(changeData.cid);
  1322. if (!result) {
  1323. throw '重新审批失败';
  1324. }
  1325. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1326. ctx.body = {
  1327. err: 0,
  1328. url: ctx.request.header.referer,
  1329. msg: '',
  1330. };
  1331. } catch (err) {
  1332. console.log(err);
  1333. // ctx.redirect(ctx.request.header.referer);
  1334. ctx.body = {
  1335. err: 1,
  1336. // url: ctx.request.header.referer,
  1337. msg: err,
  1338. };
  1339. }
  1340. }
  1341. /**
  1342. * 变更令修订重新上报
  1343. * @param {Object} ctx - egg全局变量
  1344. * @return {void}
  1345. */
  1346. async checkRevise(ctx) {
  1347. try {
  1348. const changeData = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1349. if (!changeData) {
  1350. throw '变更令数据错误';
  1351. }
  1352. if (changeData.status !== audit.flow.status.checked || ctx.session.sessionUser.accountId !== changeData.uid) {
  1353. throw '您无权进行该操作';
  1354. }
  1355. if (ctx.session.sessionUser.loginStatus === 0) {
  1356. const code = ctx.request.body.code;
  1357. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1358. if (!pa.auth_mobile) {
  1359. throw '未绑定手机号';
  1360. }
  1361. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1362. const cacheCode = await app.redis.get(cacheKey);
  1363. // console.log(cacheCode);
  1364. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1365. throw '验证码不正确!';
  1366. }
  1367. }
  1368. // 获取是否已存在调用变更令
  1369. // const changeUsedData = await ctx.service.stageChange.getFinalUsedData(ctx.tender.id, changeData.cid);
  1370. // const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.used_qty); }));
  1371. // if (stageChangeNum !== 0) {
  1372. // throw '该变更令已被调用,无法重新审批';
  1373. // }
  1374. // 重新审批
  1375. const result = await ctx.service.change.checkRevise(changeData.cid);
  1376. if (!result) {
  1377. throw '修订发起失败';
  1378. }
  1379. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1380. ctx.body = {
  1381. err: 0,
  1382. url: ctx.request.header.referer,
  1383. msg: '',
  1384. };
  1385. } catch (err) {
  1386. console.log(err);
  1387. // ctx.redirect(ctx.request.header.referer);
  1388. ctx.body = {
  1389. err: 1,
  1390. // url: ctx.request.header.referer,
  1391. msg: err,
  1392. };
  1393. }
  1394. }
  1395. /**
  1396. * 获取变更清单
  1397. * @param ctx
  1398. * @return {Promise<void>}
  1399. */
  1400. async bills(ctx) {
  1401. try {
  1402. const data = JSON.parse(ctx.request.body.data);
  1403. const responseData = { err: 0, msg: '', data: [] };
  1404. switch (data.type) {
  1405. case 'gather':
  1406. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  1407. break;
  1408. default:
  1409. throw '查询的数据不存在';
  1410. }
  1411. ctx.body = responseData;
  1412. } catch (err) {
  1413. this.log(err);
  1414. this.ajaxErrorBody(err, '获取变更清单失败');
  1415. }
  1416. }
  1417. /**
  1418. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  1419. * @param ctx
  1420. * @return {Promise<void>}
  1421. */
  1422. async checkCodeRepeat(ctx) {
  1423. const responseData = {
  1424. err: 0,
  1425. msg: '',
  1426. data: '',
  1427. };
  1428. try {
  1429. const tenderId = ctx.params.id;
  1430. const cid = ctx.params.cid;
  1431. const data = JSON.parse(ctx.request.body.data);
  1432. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  1433. if (result) {
  1434. throw '该变更令号(批复编号)已使用';
  1435. }
  1436. } catch (err) {
  1437. responseData.err = 1;
  1438. responseData.msg = err;
  1439. }
  1440. ctx.body = responseData;
  1441. }
  1442. /**
  1443. * 拷贝其他变更令
  1444. * @param {object} ctx - 全局上下文
  1445. */
  1446. async copyChange(ctx) {
  1447. const responseData = {
  1448. err: 0,
  1449. msg: '',
  1450. data: '',
  1451. };
  1452. try {
  1453. const cid = ctx.params.cid;
  1454. const copy_cid = JSON.parse(ctx.request.body.data);
  1455. const result = await ctx.service.change.handleCopyChange(cid, copy_cid);
  1456. if (!result) {
  1457. responseData.err = 1;
  1458. responseData.msg = '拷贝失败!';
  1459. }
  1460. } catch (error) {
  1461. responseData.err = 1;
  1462. responseData.msg = error;
  1463. }
  1464. ctx.body = responseData;
  1465. }
  1466. /**
  1467. * 修订 详细页面(Get)
  1468. * @param ctx
  1469. * @return {Promise<void>}
  1470. */
  1471. async reviseInfo(ctx) {
  1472. try {
  1473. if (!ctx.session.sessionProject.page_show.openChangeRevise) {
  1474. throw '该功能已关闭';
  1475. }
  1476. const change = ctx.change;
  1477. let edit = true;
  1478. let changing = false;
  1479. if (change.status !== audit.flow.status.uncheck && change.status !== audit.flow.status.back && change.status !== audit.flow.status.revise) {
  1480. // throw '本条变更审批中或已完成,无法操作台账数据';
  1481. edit = false;
  1482. changing = true;
  1483. }
  1484. let revising = false;
  1485. // 判断是否在修订中,是则无法操作本页
  1486. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  1487. if (lastRevise && lastRevise.status !== audit.revise.status.checked) {
  1488. // throw '台账修订中,无法操作台账数据';
  1489. edit = false;
  1490. revising = true;
  1491. }
  1492. const renderData = await this._getDefaultReviseInfoData(ctx, change, edit);
  1493. // 台账只读、使用数据
  1494. renderData.readOnly = !edit;
  1495. renderData.changing = changing;
  1496. renderData.revising = revising;
  1497. await this.layout('change/revise.ejs', renderData, 'change/revise_modal.ejs');
  1498. } catch (err) {
  1499. this.log(err);
  1500. ctx.redirect(ctx.request.header.referer);
  1501. }
  1502. }
  1503. async _getDefaultReviseInfoData(ctx, change, edit) {
  1504. const [ledgerSpread, posSpread] = this._getSpreadSetting(change, edit);
  1505. const sjsRela = await this.ctx.service.project.getSjsRela(ctx.session.sessionProject.id);
  1506. this.ctx.helper.refreshSpreadShow(sjsRela.ledgerCol, [ledgerSpread, posSpread]);
  1507. const [stdBills, stdChapters] = await this.ctx.service.valuation.getValuationStdList(
  1508. ctx.tender.data.valuation, ctx.tender.data.measure_type);
  1509. return {
  1510. change,
  1511. tender: ctx.tender.data,
  1512. ledgerSpread, posSpread, tenderMenu, measureType,
  1513. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  1514. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.revise),
  1515. stdBills,
  1516. auditConst: audit.flow,
  1517. audit: audit.flow,
  1518. stdChapters,
  1519. };
  1520. }
  1521. /**
  1522. * 获取SpreadSetting
  1523. * @private
  1524. */
  1525. _getSpreadSetting(change, edit) {
  1526. const _ = this.app._;
  1527. function removeFieldCols(setting, cols) {
  1528. _.remove(setting.cols, function(c) {
  1529. return cols.indexOf(c.field) > -1;
  1530. });
  1531. }
  1532. const tender = this.ctx.tender;
  1533. const setting = tender.data.measure_type === measureType.tz.value
  1534. ? (tender.info.display.ledger.clQty ? spreadConst.withCl : spreadConst.withoutCl)
  1535. : (tender.info.display.ledger.clQty ? spreadConst.withClGcl : spreadConst.withoutClGcl);
  1536. const ledger = JSON.parse(JSON.stringify(setting.ledger));
  1537. const pos = setting.pos ? JSON.parse(JSON.stringify(setting.pos)) : spreadConst.blank;
  1538. // if (change.status === audit.flow.status.checking || change.status === audit.flow.status.checked) {
  1539. // ledger.readOnly = true;
  1540. // pos.readOnly = true;
  1541. // }
  1542. if (!edit) {
  1543. ledger.readOnly = true;
  1544. pos.readOnly = true;
  1545. }
  1546. if (tender.data.measure_type === measureType.tz.value) {
  1547. removeFieldCols(ledger, spreadConst.filterCols.tzWithoutCols);
  1548. }
  1549. if (!tender.info.display.ledger.dgnQty) {
  1550. removeFieldCols(ledger, spreadConst.filterCols.dgnCols);
  1551. }
  1552. return [ledger, pos];
  1553. }
  1554. async updateRevise(ctx) {
  1555. try {
  1556. if (!ctx.tender.data) throw '标段数据错误';
  1557. if (!ctx.session.sessionProject.page_show.openChangeRevise) {
  1558. throw '该功能已关闭';
  1559. }
  1560. const data = JSON.parse(ctx.request.body.data);
  1561. if (!data.postType || !data.postData) throw '数据错误';
  1562. const responseData = { err: 0, msg: '', data: {} };
  1563. const change = ctx.change;
  1564. if (change.status !== audit.flow.status.uncheck && change.status !== audit.flow.status.back && change.status !== audit.flow.status.revise) {
  1565. throw '该变更令正在审批中或已完成,无法操作新增部位数据';
  1566. }
  1567. // 判断是否在修订中,是则无法操作本页
  1568. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  1569. if (lastRevise && lastRevise.status !== audit.revise.status.checked) {
  1570. throw '台账修订中,无法操作新增部位数据';
  1571. }
  1572. // const revise = await this.checkRevise(ctx);
  1573. //
  1574. switch (data.postType) {
  1575. case 'add':
  1576. case 'delete':
  1577. case 'up-move':
  1578. case 'down-move':
  1579. case 'up-level':
  1580. case 'down-level':
  1581. responseData.data = await this._billsBase(ctx, data.postType, data.postData);
  1582. break;
  1583. case 'update':
  1584. ctx.helper.checkDgnQtyPrecision(data.postData);
  1585. responseData.data = await ctx.service.changeLedger.updateCalc(ctx.tender.id, data.postData);
  1586. break;
  1587. case 'paste-block':
  1588. responseData.data = await this._pasteBlock(ctx, data.postData);
  1589. break;
  1590. case 'add-std':
  1591. responseData.data = await this._addStd(ctx, data.postData);
  1592. break;
  1593. case 'add-deal':
  1594. responseData.data = await this._addDeal(ctx, data.postData);
  1595. break;
  1596. // case 'batch-insert':
  1597. // responseData.data = await this._batchInsert(ctx, data.postData);
  1598. // break;
  1599. case 'pos':
  1600. responseData.data = await this._updatePos(ctx, data);
  1601. break;
  1602. default:
  1603. throw '未知操作';
  1604. }
  1605. ctx.body = responseData;
  1606. } catch (err) {
  1607. this.log(err);
  1608. ctx.body = this.ajaxErrorBody(err, '数据错误');
  1609. }
  1610. }
  1611. async _billsBase(ctx, type, data) {
  1612. if (isNaN(data.id) || data.id <= 0) throw '数据错误';
  1613. if (type !== 'add') {
  1614. if (isNaN(data.count) || data.count <= 0) data.count = 1;
  1615. }
  1616. switch (type) {
  1617. case 'add':
  1618. return await ctx.service.changeLedger.addNodeBatch(ctx.tender.id, data.id, { ccid: ctx.change.cid, check_calc: 1 }, data.count);
  1619. case 'delete':
  1620. return await ctx.service.changeLedger.delete(ctx.tender.id, data.id, data.count);
  1621. case 'up-move':
  1622. return await ctx.service.changeLedger.upMoveNode(ctx.tender.id, data.id, data.count);
  1623. case 'down-move':
  1624. return await ctx.service.changeLedger.downMoveNode(ctx.tender.id, data.id, data.count);
  1625. case 'up-level':
  1626. return await ctx.service.changeLedger.upLevelNode(ctx.tender.id, data.id, data.count);
  1627. case 'down-level':
  1628. return await ctx.service.changeLedger.downLevelNode(ctx.tender.id, data.id, data.count);
  1629. default:
  1630. throw '未知操作';
  1631. }
  1632. }
  1633. /**
  1634. * 复制粘贴整块
  1635. *
  1636. * @param ctx
  1637. * @return {Promise<void>}
  1638. */
  1639. async _pasteBlock(ctx, data) {
  1640. if ((isNaN(data.id) || data.id <= 0) ||
  1641. (!data.tid && data.tid <= 0) ||
  1642. (!data.block || data.block.length <= 0)) throw '参数错误';
  1643. return await ctx.service.changeLedger.pasteBlockData(ctx.tender.id, data.id, data.block);
  1644. }
  1645. /**
  1646. * 从标准项目表添加数据
  1647. * @param ctx
  1648. * @return {Promise<void>}
  1649. */
  1650. async _addStd(ctx, data) {
  1651. if ((isNaN(data.id) || data.id <= 0) || !data.stdType || !data.stdNode) throw '参数错误';
  1652. // todo 校验项目是否使用该库的权限
  1653. let stdLib,
  1654. addType;
  1655. switch (data.stdType) {
  1656. case 'xmj':
  1657. stdLib = ctx.service.stdXmj;
  1658. addType = stdDataAddType.withParent;
  1659. break;
  1660. case 'gcl':
  1661. stdLib = ctx.service.stdGcl;
  1662. const selectNode = await ctx.service.changeLedger.getDataByNodeId(ctx.tender.id, data.id) || await ctx.service.ledger.getDataByNodeId(ctx.tender.id, data.id);
  1663. if (selectNode.b_code) {
  1664. addType = stdDataAddType.next;
  1665. } else {
  1666. addType = stdDataAddType.child;
  1667. }
  1668. break;
  1669. default:
  1670. throw '未知标准库';
  1671. }
  1672. const stdData = await stdLib.getDataByDataId(data.stdLibId, data.stdNode);
  1673. switch (addType) {
  1674. case stdDataAddType.child:
  1675. return await ctx.service.changeLedger.addStdNodeAsChild(ctx.tender.id, data.id, stdData, ctx.change.cid);
  1676. case stdDataAddType.next:
  1677. return await ctx.service.changeLedger.addStdNode(ctx.tender.id, data.id, stdData, ctx.change.cid);
  1678. case stdDataAddType.withParent:
  1679. return await ctx.service.changeLedger.addStdNodeWithParent(ctx.tender.id, stdData, stdLib, ctx.change.cid);
  1680. default:
  1681. throw '未知添加方式';
  1682. }
  1683. }
  1684. /**
  1685. * 从签约清单添加节点
  1686. * @param ctx
  1687. * @return {Promise<void>}
  1688. */
  1689. async _addDeal(ctx, data) {
  1690. if (!data.type || !data.dealBills) throw '数据错误';
  1691. data.dealBills.unit_price = this.ctx.helper.round(data.dealBills.unit_price, ctx.tender.info.decimal.up);
  1692. if (data.type === 'child') {
  1693. return await ctx.service.changeLedger.addChild(ctx.tender.id, data.id, data.dealBills, ctx.change.cid);
  1694. } else if (data.type === 'next') {
  1695. data.dealBills.ccid = ctx.change.cid;
  1696. return await ctx.service.changeLedger.addNode(ctx.tender.id, data.id, data.dealBills);
  1697. }
  1698. throw '数据错误';
  1699. }
  1700. /**
  1701. * 批量插入数据
  1702. *
  1703. * data = {id, batchData, batchType}
  1704. * data.batchType = 'batchInsertChild'/'batchInsertNext'
  1705. * data.batchData = [{name, children}] -- 项目节列表
  1706. * data.batchData.children = [{code, name, unit, unit_price, quantity}] -- 工程量清单列表
  1707. *
  1708. * @param ctx
  1709. * @return {Promise<void>}
  1710. */
  1711. async _batchInsert(ctx, data) {
  1712. if ((isNaN(data.id) || data.id <= 0) || !data.batchType) throw '参数错误';
  1713. switch (data.batchType) {
  1714. case 'child':
  1715. return await ctx.service.changeLedger.batchInsertChild(ctx.tender.id, data.id, data.batchData);
  1716. case 'next':
  1717. return await ctx.service.changeLedger.batchInsertNext(ctx.tender.id, data.id, data.batchData);
  1718. default:
  1719. throw '参数错误';
  1720. }
  1721. }
  1722. async _updatePos(ctx, data) {
  1723. await this.checkMeasureType(measureType.tz.value);
  1724. if (!data.posPostType) throw '数据错误';
  1725. switch (data.posPostType) {
  1726. case 'add':
  1727. return await this.ctx.service.changePos.addPos(ctx.tender.id, ctx.change.cid, data.postData);
  1728. case 'update':
  1729. if (data.postData instanceof Array) {
  1730. return await this.ctx.service.changePos.updatePosArr(ctx.tender.id, data.postData);
  1731. }
  1732. return await this.ctx.service.changePos.updatePos(ctx.tender.id, data.postData);
  1733. case 'delete':
  1734. return await this.ctx.service.changePos.deletePos(ctx.tender.id, data.postData);
  1735. case 'paste':
  1736. return await this.ctx.service.changePos.pastePosData(ctx.tender.id, ctx.change.cid, data.postData);
  1737. default:
  1738. throw '未知操作';
  1739. }
  1740. }
  1741. async _filterChangesProject(ctx, status = 0) {
  1742. const tenderId = ctx.params.id;
  1743. ctx.session.sessionUser.tenderId = tenderId;
  1744. const tender = await this.service.tender.getDataById(ctx.tender.id);
  1745. // const tender = ctx.tender;
  1746. // const tenderList = await this.service.tender.getList();
  1747. const page = ctx.page;
  1748. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  1749. const orders = ctx.query.order ? ctx.query.order : 0;
  1750. const changes = await ctx.service.changeProject.getListByStatus(tender.id, status, 1, sorts, orders);
  1751. const total = await ctx.service.changeProject.getCountByStatus(tender.id, status);
  1752. for (const c of changes) {
  1753. c.curAuditor = await ctx.service.changeProjectAudit.getAuditorByStatus(c.id, c.status, c.times);
  1754. }
  1755. const accountInfo = await this.ctx.service.projectAccount.getDataById(this.ctx.session.sessionUser.accountId);
  1756. const userPermission = accountInfo !== undefined && accountInfo.permission !== ''
  1757. ? JSON.parse(accountInfo.permission) : null;
  1758. // 分页相关
  1759. const pageInfo = {
  1760. page,
  1761. total: Math.ceil(total / app.config.pageSize),
  1762. queryData: JSON.stringify(ctx.urlInfo.query),
  1763. };
  1764. const filter = JSON.parse(JSON.stringify(audit.changeProject.filter));
  1765. filter.count = [];
  1766. filter.count[filter.status.pending] = await ctx.service.changeProject.getCountByStatus(tender.id, filter.status.pending);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  1767. filter.count[filter.status.uncheck] = await ctx.service.changeProject.getCountByStatus(tender.id, filter.status.uncheck);// await ctx.service.change.checkingDatas(tender.id, ctx.session.sessionUser.accountId);
  1768. filter.count[filter.status.checking] = await ctx.service.changeProject.getCountByStatus(tender.id, filter.status.checking);// await ctx.service.change.checkedDatas(tender.id, ctx.session.sessionUser.accountId);
  1769. filter.count[filter.status.checked] = await ctx.service.changeProject.getCountByStatus(tender.id, filter.status.checked);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  1770. filter.count[filter.status.checkNo] = await ctx.service.changeProject.getCountByStatus(tender.id, filter.status.checkNo);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  1771. let codeRule = [];
  1772. let c_connector = '1';
  1773. let c_rule_first = 1;
  1774. const rule_type = tender.user_id === ctx.session.sessionUser.accountId ? 'suggestion' : 'will';
  1775. if (tender.c_code_rules) {
  1776. const c_code_rules = JSON.parse(tender.c_code_rules);
  1777. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  1778. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  1779. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  1780. }
  1781. for (const rule of codeRule) {
  1782. switch (rule.rule_type) {
  1783. case codeRuleConst.measure.ruleType.dealCode:
  1784. rule.preview = ctx.tender.info.deal_info.dealCode;
  1785. break;
  1786. case codeRuleConst.measure.ruleType.tenderName:
  1787. rule.preview = tender.name;
  1788. break;
  1789. case codeRuleConst.measure.ruleType.inDate:
  1790. rule.preview = moment().format('YYYY');
  1791. break;
  1792. case codeRuleConst.measure.ruleType.text:
  1793. rule.preview = rule.text;
  1794. break;
  1795. case codeRuleConst.measure.ruleType.addNo:
  1796. const s = '0000000000';
  1797. rule.preview = s.substr(s.length - rule.format);
  1798. break;
  1799. default: break;
  1800. }
  1801. }
  1802. const renderData = {
  1803. uid: ctx.session.sessionUser.accountId,
  1804. userPermission,
  1805. tender,
  1806. pageInfo,
  1807. changes,
  1808. status,
  1809. rule_type,
  1810. codeRule,
  1811. c_connector,
  1812. c_rule_first,
  1813. filter,
  1814. ruleType: codeRuleConst.ruleType[rule_type],
  1815. dealCode: ctx.tender.info.deal_info.dealCode,
  1816. auditConst: audit.changeProject,
  1817. ruleConst: codeRuleConst.measure,
  1818. changeConst,
  1819. tenderMenu: this.menu.tenderMenu,
  1820. preUrl: '/tender/' + tender.id,
  1821. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.project),
  1822. };
  1823. await this.layout('change/project.ejs', renderData, 'change/project_modal.ejs');
  1824. }
  1825. /**
  1826. * 变更立项列表 页面 (Get)
  1827. *
  1828. * @param {Object} ctx - egg全局变量
  1829. * @return {void}
  1830. */
  1831. async project(ctx) {
  1832. try {
  1833. await this._filterChangesProject(ctx);
  1834. } catch (err) {
  1835. this.log(err);
  1836. ctx.redirect('/dashboard');
  1837. }
  1838. }
  1839. /**
  1840. * 新增变更立项 (Post)
  1841. *
  1842. * @param {Object} ctx - egg全局变量
  1843. * @return {void}
  1844. */
  1845. async projectAdd(ctx) {
  1846. try {
  1847. const tenderId = ctx.params.id;
  1848. if (!tenderId) {
  1849. throw '当前未打开标段';
  1850. }
  1851. const data = JSON.parse(ctx.request.body.data);
  1852. if (!data.code || data.code === '' || !data.name || data.name === '') {
  1853. throw '变更立项书编号不能为空';
  1854. }
  1855. const change = await ctx.service.changeProject.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  1856. ctx.body = { err: 0, msg: '', data: change };
  1857. } catch (err) {
  1858. this.log(err);
  1859. ctx.body = { err: 1, msg: err.toString() };
  1860. }
  1861. }
  1862. /**
  1863. * 删除变更立项
  1864. * @param {Object} ctx - egg全局变量
  1865. * @return {void}
  1866. */
  1867. async projectDelete(ctx) {
  1868. try {
  1869. const result = await ctx.service.changeProject.delete(ctx.request.body.cpid);
  1870. if (!result) {
  1871. throw '删除变更立项失败';
  1872. }
  1873. ctx.redirect(ctx.request.header.referer);
  1874. } catch (err) {
  1875. console.log(err);
  1876. ctx.redirect(ctx.request.header.referer);
  1877. }
  1878. }
  1879. /**
  1880. * 变更管理 状态筛选 页面 (Get)
  1881. * @param {Object} ctx - egg全局变量
  1882. * @return {void}
  1883. */
  1884. async projectStatus(ctx) {
  1885. try {
  1886. const status = parseInt(ctx.params.status);
  1887. await this._filterChangesProject(ctx, status);
  1888. } catch (err) {
  1889. this.logger.error(err);
  1890. ctx.redirect('/tender/' + ctx.params.id + '/change/project');
  1891. }
  1892. }
  1893. /**
  1894. * 获取审批界面所需的 原报、审批人数据等
  1895. * @param ctx
  1896. * @return {Promise<void>}
  1897. * @private
  1898. */
  1899. async _getChangeProjectAuditViewData(ctx) {
  1900. const auditConst = audit.changeProject;
  1901. const times = ctx.change.status === auditConst.status.back ? ctx.change.times - 1 : ctx.change.times;
  1902. ctx.change.user = await ctx.service.projectAccount.getAccountInfoById(ctx.change.uid);
  1903. ctx.change.auditHistory = [];
  1904. if (times >= 1) {
  1905. for (let i = 1; i <= times; i++) {
  1906. ctx.change.auditHistory.push(await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, i));
  1907. }
  1908. }
  1909. // 获取审批流程中左边列表
  1910. ctx.change.auditors2 = ctx.change.status === auditConst.status.back && ctx.change.user_id !== ctx.session.sessionUser.accountId ?
  1911. await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, times) :
  1912. await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  1913. if (ctx.change.status === auditConst.status.uncheck || ctx.change.status === auditConst.status.back) {
  1914. ctx.change.auditorList = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  1915. }
  1916. ctx.change.xsAuditors = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  1917. }
  1918. async projectInformation(ctx) {
  1919. try {
  1920. const whiteList = this.ctx.app.config.multipart.whitelist;
  1921. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  1922. // 获取附件列表
  1923. const fileList = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  1924. await this._getChangeProjectAuditViewData(ctx);
  1925. const renderData = {
  1926. tender,
  1927. change: ctx.change,
  1928. changeConst,
  1929. auditConst: audit.changeProject,
  1930. fileList,
  1931. whiteList,
  1932. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.project_information),
  1933. preUrl: '/tender/' + ctx.tender.id + '/change/project/' + ctx.change.id + '/information',
  1934. };
  1935. // if ((ctx.change.status === audit.changeProject.status.uncheck || ctx.change.status === audit.changeProject.status.back) && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.tender.isTourist)) {
  1936. // data.accountGroup = accountGroup;
  1937. // 获取所有项目参与者
  1938. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  1939. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  1940. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  1941. });
  1942. renderData.accountList = accountList;
  1943. renderData.accountGroup = accountGroup.map((item, idx) => {
  1944. const groupList = accountList.filter(item => item.account_group === idx);
  1945. return { groupName: item, groupList };
  1946. });
  1947. // }
  1948. await this.layout('change/project_information.ejs', renderData, 'change/project_information_modal.ejs');
  1949. } catch (err) {
  1950. this.log(err);
  1951. ctx.redirect('/tender/' + ctx.params.id + '/change');
  1952. }
  1953. }
  1954. // 审批相关
  1955. /**
  1956. * 添加审批人
  1957. * @param ctx
  1958. * @return {Promise<void>}
  1959. */
  1960. async addProjectAudit(ctx) {
  1961. try {
  1962. const auditConst = audit.changeProject;
  1963. const data = JSON.parse(ctx.request.body.data);
  1964. const id = this.app._.toInteger(data.auditorId);
  1965. if (isNaN(id) || id <= 0) {
  1966. throw '参数错误';
  1967. }
  1968. // 检查权限等
  1969. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  1970. throw '您无权添加审核人';
  1971. }
  1972. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  1973. throw '当前不允许添加审核人';
  1974. }
  1975. // 判断是否是协审人,是则无法添加到审批人中
  1976. const xsAuditorList = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  1977. const xsAidList = this.app._.map(xsAuditorList, 'aid');
  1978. if (this.app._.indexOf(xsAidList, id) !== -1) {
  1979. throw '该用户已添加到协审人列表中,请删除该协审人再添加';
  1980. }
  1981. ctx.change.auditorList = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  1982. // 检查审核人是否已存在
  1983. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  1984. if (exist) {
  1985. throw '该审核人已存在,请勿重复添加';
  1986. }
  1987. // const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.material, sp_status: shenpiConst.sp_status.gdzs });
  1988. // const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs ? 1 : 0;
  1989. const result = await ctx.service.changeProjectAudit.addAuditor(ctx.change.id, id, ctx.change.times);
  1990. if (!result) {
  1991. throw '添加审核人失败';
  1992. }
  1993. const auditors = await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  1994. ctx.body = { err: 0, msg: '', data: auditors };
  1995. } catch (err) {
  1996. this.log(err);
  1997. ctx.body = { err: 1, msg: err.toString(), data: null };
  1998. }
  1999. }
  2000. /**
  2001. * 移除审批人
  2002. * @param ctx
  2003. * @return {Promise<void>}
  2004. */
  2005. async deleteProjectAudit(ctx) {
  2006. try {
  2007. const data = JSON.parse(ctx.request.body.data);
  2008. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  2009. if (isNaN(id) || id <= 0) {
  2010. throw '参数错误';
  2011. }
  2012. const result = await ctx.service.changeProjectAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  2013. if (!result) {
  2014. throw '移除审核人失败';
  2015. }
  2016. const auditors = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  2017. ctx.body = { err: 0, msg: '', data: auditors };
  2018. } catch (err) {
  2019. ctx.body = { err: 1, msg: err.toString(), data: null };
  2020. }
  2021. }
  2022. /**
  2023. * 添加协审人
  2024. * @param ctx
  2025. * @return {Promise<void>}
  2026. */
  2027. async addProjectXsAudit(ctx) {
  2028. try {
  2029. const auditConst = audit.changeProject;
  2030. const data = JSON.parse(ctx.request.body.data);
  2031. const id = this.app._.toInteger(data.auditorId);
  2032. if (isNaN(id) || id <= 0) {
  2033. throw '参数错误';
  2034. }
  2035. const times = ctx.change.status === auditConst.status.back ? ctx.change.times - 1 : ctx.change.times;
  2036. const spAuditors = await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, times);
  2037. const aidLists = this.app._.map(spAuditors, 'aid');
  2038. // 检查权限等
  2039. if (this.app._.indexOf(aidLists, ctx.session.sessionUser.accountId) === -1) {
  2040. throw '您无权添加协审人';
  2041. }
  2042. // 如果已经是审批人则无法添加此人为协审
  2043. if (this.app._.indexOf(aidLists, id) !== -1) {
  2044. throw '该用户为审批人或原报,无需添加至协审人';
  2045. }
  2046. const auditorList = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  2047. // 检查审核人是否已存在
  2048. const exist = this.app._.find(auditorList, { aid: id });
  2049. if (exist) {
  2050. throw '该协审人已存在,请勿重复添加';
  2051. }
  2052. const result = await ctx.service.changeProjectXsAudit.addAuditor(ctx.change.id, id);
  2053. if (!result) {
  2054. throw '添加协审人失败';
  2055. }
  2056. const auditors = await ctx.service.changeProjectXsAudit.getOneAudit(ctx.change.id, id);
  2057. ctx.body = { err: 0, msg: '', data: auditors };
  2058. } catch (err) {
  2059. this.log(err);
  2060. ctx.body = { err: 1, msg: err.toString(), data: null };
  2061. }
  2062. }
  2063. /**
  2064. * 移除协审人
  2065. * @param ctx
  2066. * @return {Promise<void>}
  2067. */
  2068. async deleteProjectXsAudit(ctx) {
  2069. try {
  2070. const data = JSON.parse(ctx.request.body.data);
  2071. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  2072. if (isNaN(id) || id <= 0) {
  2073. throw '参数错误';
  2074. }
  2075. const result = await ctx.service.changeProjectXsAudit.deleteAuditor(ctx.change.id, id);
  2076. if (!result) {
  2077. throw '移除协审人失败';
  2078. }
  2079. const auditors = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  2080. ctx.body = { err: 0, msg: '', data: auditors };
  2081. } catch (err) {
  2082. ctx.body = { err: 1, msg: err.toString(), data: null };
  2083. }
  2084. }
  2085. /**
  2086. * 上传附件
  2087. * @param {*} ctx 上下文
  2088. */
  2089. async uploadProjectFile(ctx) {
  2090. let stream;
  2091. try {
  2092. const auditConst = audit.changeProject;
  2093. // this._checkAdvanceFileCanModify(ctx);
  2094. const parts = this.ctx.multipart({
  2095. autoFields: true,
  2096. });
  2097. const files = [];
  2098. const create_time = Date.parse(new Date()) / 1000;
  2099. let idx = 0;
  2100. const extra_upload = ctx.change.status === auditConst.status.checked;
  2101. while ((stream = await parts()) !== undefined) {
  2102. if (!stream.filename) {
  2103. // 如果没有传入直接返回
  2104. return;
  2105. }
  2106. const fileInfo = path.parse(stream.filename);
  2107. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_project/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  2108. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  2109. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  2110. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  2111. ++idx;
  2112. stream && (await sendToWormhole(stream));
  2113. }
  2114. const in_time = new Date();
  2115. const payload = files.map(file => {
  2116. let idx;
  2117. if (Array.isArray(parts.field.name)) {
  2118. idx = parts.field.name.findIndex(name => name === file.name);
  2119. } else {
  2120. idx = 'isString';
  2121. }
  2122. const newFile = {
  2123. tid: ctx.tender.id,
  2124. cpid: ctx.change.id,
  2125. uid: ctx.session.sessionUser.accountId,
  2126. filename: file.name,
  2127. fileext: file.ext,
  2128. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  2129. filepath: file.filepath,
  2130. upload_time: in_time,
  2131. extra_upload,
  2132. };
  2133. return newFile;
  2134. });
  2135. // 执行文件信息写入数据库
  2136. await ctx.service.changeProjectAtt.saveFileMsgToDb(payload);
  2137. // 将最新的当前标段的所有文件信息返回
  2138. const data = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2139. ctx.body = { err: 0, msg: '', data };
  2140. } catch (err) {
  2141. stream && (await sendToWormhole(stream));
  2142. this.log(err);
  2143. ctx.body = { err: 1, msg: err.toString(), data: null };
  2144. }
  2145. }
  2146. /**
  2147. * 删除附件
  2148. * @param {Ojbect} ctx 上下文
  2149. */
  2150. async deleteProjectFile(ctx) {
  2151. try {
  2152. const { id } = JSON.parse(ctx.request.body.data);
  2153. const fileInfo = await ctx.service.changeProjectAtt.getDataById(id);
  2154. if (fileInfo || Object.keys(fileInfo).length) {
  2155. // 先删除文件
  2156. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  2157. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  2158. // 再删除数据库
  2159. await ctx.service.changeProjectAtt.delete(id);
  2160. } else {
  2161. throw '不存在该文件';
  2162. }
  2163. const data = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2164. ctx.body = { err: 0, msg: '请求成功', data };
  2165. } catch (err) {
  2166. this.log(err);
  2167. ctx.body = { err: 1, msg: err.toString(), data: null };
  2168. }
  2169. }
  2170. /**
  2171. * 下载附件
  2172. * @param {Object} ctx - egg全局变量
  2173. * @return {void}
  2174. */
  2175. async downloadProjectFile(ctx) {
  2176. const id = ctx.params.fid;
  2177. if (id) {
  2178. try {
  2179. const fileInfo = await ctx.service.changeProjectAtt.getDataById(id);
  2180. if (fileInfo !== undefined && fileInfo !== '') {
  2181. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  2182. // 解决中文无法下载问题
  2183. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  2184. let disposition = '';
  2185. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  2186. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  2187. } else if (userAgent.indexOf('firefox') >= 0) {
  2188. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  2189. } else {
  2190. /* safari等其他非主流浏览器只能自求多福了 */
  2191. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  2192. }
  2193. ctx.response.set({
  2194. 'Content-Type': 'application/octet-stream',
  2195. 'Content-Disposition': disposition,
  2196. 'Content-Length': fileInfo.filesize,
  2197. });
  2198. // ctx.body = await fs.createReadStream(fileName);
  2199. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  2200. } else {
  2201. throw '不存在该文件';
  2202. }
  2203. } catch (err) {
  2204. this.log(err);
  2205. this.setMessage(err.toString(), this.messageType.ERROR);
  2206. }
  2207. }
  2208. }
  2209. async projectInformationSave(ctx) {
  2210. try {
  2211. const data = JSON.parse(ctx.request.body.data);
  2212. if (data.name === 'code') {
  2213. const info = await ctx.service.changeProject.isRepeat(ctx.change.id, data.val, ctx.tender.id, ctx.change.type);
  2214. if (info) {
  2215. throw '该编号已存在';
  2216. }
  2217. }
  2218. const result = await ctx.service.changeProject.saveInfo(ctx.change.id, data);
  2219. if (!result) {
  2220. throw '修改失败';
  2221. }
  2222. ctx.body = { err: 0, msg: '请求成功', data: null };
  2223. } catch (err) {
  2224. this.log(err);
  2225. ctx.body = { err: 1, msg: err.toString(), data: null };
  2226. }
  2227. }
  2228. /**
  2229. * 上报和重新上报
  2230. * @param ctx
  2231. * @return {Promise<void>}
  2232. */
  2233. async startProjectAudit(ctx) {
  2234. try {
  2235. const auditConst = audit.changeProject;
  2236. // 检查权限等
  2237. if (!ctx.change) {
  2238. throw '数据错误';
  2239. }
  2240. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2241. throw '您无权上报该期数据';
  2242. }
  2243. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2244. throw '该材料调差期数据当前无法上报';
  2245. }
  2246. await ctx.service.changeProjectAudit.start(ctx.change.id, ctx.change.times);
  2247. ctx.redirect(ctx.request.header.referer);
  2248. } catch (err) {
  2249. this.log(err);
  2250. ctx.session.postError = err.toString();
  2251. ctx.redirect(ctx.request.header.referer);
  2252. }
  2253. }
  2254. /**
  2255. * 审批
  2256. * @param ctx
  2257. * @return {Promise<void>}
  2258. */
  2259. async checkProjectAudit(ctx) {
  2260. try {
  2261. const auditConst = audit.changeProject;
  2262. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  2263. throw '当前材料调差期数据有误';
  2264. }
  2265. if (!ctx.change.curAuditor || ctx.change.curAuditor.aid !== ctx.session.sessionUser.accountId) {
  2266. throw '您无权进行该操作';
  2267. }
  2268. const data = {
  2269. checkType: parseInt(ctx.request.body.checkType),
  2270. opinion: ctx.request.body.opinion,
  2271. };
  2272. if (!data.checkType || isNaN(data.checkType)) {
  2273. throw '提交数据错误';
  2274. }
  2275. // if (data.checkType === auditConst.status.checkNo) {
  2276. // if (!data.checkType || isNaN(data.checkType)) {
  2277. // throw '提交数据错误';
  2278. // }
  2279. // }
  2280. await ctx.service.changeProjectAudit.check(ctx.change.id, data, ctx.change.times);
  2281. ctx.redirect(ctx.request.header.referer);
  2282. } catch (err) {
  2283. this.log(err);
  2284. ctx.session.postError = err.toString();
  2285. ctx.redirect(ctx.request.header.referer);
  2286. }
  2287. }
  2288. async _filterChangesApply(ctx, status = 0) {
  2289. const tenderId = ctx.params.id;
  2290. ctx.session.sessionUser.tenderId = tenderId;
  2291. const tender = await this.service.tender.getDataById(ctx.tender.id);
  2292. // const tender = ctx.tender;
  2293. // const tenderList = await this.service.tender.getList();
  2294. const page = ctx.page;
  2295. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  2296. const orders = ctx.query.order ? ctx.query.order : 0;
  2297. const changes = await ctx.service.changeApply.getListByStatus(tender.id, status, 1, sorts, orders);
  2298. const total = await ctx.service.changeApply.getCountByStatus(tender.id, status);
  2299. for (const c of changes) {
  2300. c.curAuditor = await ctx.service.changeApplyAudit.getAuditorByStatus(c.id, c.status, c.times);
  2301. }
  2302. const tender_userInfo = await ctx.service.projectAccount.getDataById(ctx.tender.data.user_id);
  2303. // 分页相关
  2304. const pageInfo = {
  2305. page,
  2306. total: Math.ceil(total / app.config.pageSize),
  2307. queryData: JSON.stringify(ctx.urlInfo.query),
  2308. };
  2309. const filter = JSON.parse(JSON.stringify(audit.changeApply.filter));
  2310. filter.count = [];
  2311. filter.count[filter.status.pending] = await ctx.service.changeApply.getCountByStatus(tender.id, filter.status.pending);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  2312. filter.count[filter.status.uncheck] = await ctx.service.changeApply.getCountByStatus(tender.id, filter.status.uncheck);// await ctx.service.change.checkingDatas(tender.id, ctx.session.sessionUser.accountId);
  2313. filter.count[filter.status.checking] = await ctx.service.changeApply.getCountByStatus(tender.id, filter.status.checking);// await ctx.service.change.checkedDatas(tender.id, ctx.session.sessionUser.accountId);
  2314. filter.count[filter.status.checked] = await ctx.service.changeApply.getCountByStatus(tender.id, filter.status.checked);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  2315. // filter.count[filter.status.checkNo] = await ctx.service.changeApply.getCountByStatus(tender.id, filter.status.checkNo);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  2316. let codeRule = [];
  2317. let c_connector = '1';
  2318. let c_rule_first = 1;
  2319. const rule_type = 'apply';
  2320. if (tender.c_code_rules) {
  2321. const c_code_rules = JSON.parse(tender.c_code_rules);
  2322. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  2323. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  2324. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  2325. }
  2326. for (const rule of codeRule) {
  2327. switch (rule.rule_type) {
  2328. case codeRuleConst.measure.ruleType.dealCode:
  2329. rule.preview = ctx.tender.info.deal_info.dealCode;
  2330. break;
  2331. case codeRuleConst.measure.ruleType.tenderName:
  2332. rule.preview = tender.name;
  2333. break;
  2334. case codeRuleConst.measure.ruleType.inDate:
  2335. rule.preview = moment().format('YYYY');
  2336. break;
  2337. case codeRuleConst.measure.ruleType.text:
  2338. rule.preview = rule.text;
  2339. break;
  2340. case codeRuleConst.measure.ruleType.addNo:
  2341. const s = '0000000000';
  2342. rule.preview = s.substr(s.length - rule.format);
  2343. break;
  2344. default: break;
  2345. }
  2346. }
  2347. const changeProjectList = await ctx.service.changeProject.getAllDataByCondition({ where: { tid: tender.id, status: audit.changeProject.status.checked } });
  2348. const renderData = {
  2349. uid: ctx.session.sessionUser.accountId,
  2350. tender,
  2351. pageInfo,
  2352. changes,
  2353. status,
  2354. rule_type,
  2355. codeRule,
  2356. c_connector,
  2357. c_rule_first,
  2358. filter,
  2359. apply_username: tender_userInfo ? tender_userInfo.name : null,
  2360. ruleType: codeRuleConst.ruleType[rule_type],
  2361. dealCode: ctx.tender.info.deal_info.dealCode,
  2362. auditConst: audit.changeApply,
  2363. ruleConst: codeRuleConst.measure,
  2364. changeConst,
  2365. changeProjectList,
  2366. tenderMenu: this.menu.tenderMenu,
  2367. preUrl: '/tender/' + tender.id,
  2368. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply),
  2369. };
  2370. await this.layout('change/apply.ejs', renderData, 'change/apply_modal.ejs');
  2371. }
  2372. /**
  2373. * 变更申请列表 页面 (Get)
  2374. *
  2375. * @param {Object} ctx - egg全局变量
  2376. * @return {void}
  2377. */
  2378. async apply(ctx) {
  2379. try {
  2380. await this._filterChangesApply(ctx);
  2381. } catch (err) {
  2382. this.log(err);
  2383. ctx.redirect('/dashboard');
  2384. }
  2385. }
  2386. /**
  2387. * 变更管理 状态筛选 页面 (Get)
  2388. * @param {Object} ctx - egg全局变量
  2389. * @return {void}
  2390. */
  2391. async applyStatus(ctx) {
  2392. try {
  2393. const status = parseInt(ctx.params.status);
  2394. await this._filterChangesApply(ctx, status);
  2395. } catch (err) {
  2396. this.logger.error(err);
  2397. ctx.redirect('/tender/' + ctx.params.id + '/change/apply');
  2398. }
  2399. }
  2400. /**
  2401. * 新增变更立项 (Post)
  2402. *
  2403. * @param {Object} ctx - egg全局变量
  2404. * @return {void}
  2405. */
  2406. async applyAdd(ctx) {
  2407. try {
  2408. const tenderId = ctx.params.id;
  2409. if (!tenderId) {
  2410. throw '当前未打开标段';
  2411. }
  2412. const data = JSON.parse(ctx.request.body.data);
  2413. if (!data.code || data.code === '') {
  2414. throw '变更申请编号不能为空';
  2415. }
  2416. const change = await ctx.service.changeApply.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.project_code);
  2417. ctx.body = { err: 0, msg: '', data: change };
  2418. } catch (err) {
  2419. this.log(err);
  2420. ctx.body = { err: 1, msg: err.toString() };
  2421. }
  2422. }
  2423. /**
  2424. * 删除变更立项
  2425. * @param {Object} ctx - egg全局变量
  2426. * @return {void}
  2427. */
  2428. async applyDelete(ctx) {
  2429. try {
  2430. const result = await ctx.service.changeApply.delete(ctx.request.body.caid);
  2431. if (!result) {
  2432. throw '删除变更立项失败';
  2433. }
  2434. ctx.redirect(ctx.request.header.referer);
  2435. } catch (err) {
  2436. console.log(err);
  2437. ctx.redirect(ctx.request.header.referer);
  2438. }
  2439. }
  2440. /**
  2441. * 获取审批界面所需的 原报、审批人数据等
  2442. * @param ctx
  2443. * @return {Promise<void>}
  2444. * @private
  2445. */
  2446. async _getChangeApplyAuditViewData(ctx) {
  2447. const auditConst = audit.changeApply;
  2448. const times = ctx.change.status === auditConst.status.checkNo ? ctx.change.times - 1 : ctx.change.times;
  2449. ctx.change.user = await ctx.service.projectAccount.getAccountInfoById(ctx.change.uid);
  2450. ctx.change.auditHistory = [];
  2451. if (times >= 1) {
  2452. for (let i = 1; i <= times; i++) {
  2453. ctx.change.auditHistory.push(await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, i));
  2454. }
  2455. }
  2456. // 获取审批流程中左边列表
  2457. ctx.change.auditors2 = ctx.change.status === auditConst.status.checkNo && ctx.change.user_id !== ctx.session.sessionUser.accountId ?
  2458. await ctx.service.changeApplyAudit.getAuditorsWithOwner(ctx.change.id, times) :
  2459. await ctx.service.changeApplyAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  2460. if (ctx.change.status === auditConst.status.uncheck || ctx.change.status === auditConst.status.checkNo) {
  2461. ctx.change.auditorList = await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, ctx.change.times);
  2462. }
  2463. }
  2464. async applyInformation(ctx) {
  2465. try {
  2466. const whiteList = this.ctx.app.config.multipart.whitelist;
  2467. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  2468. // 获取附件列表
  2469. const fileList = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2470. await this._getChangeApplyAuditViewData(ctx);
  2471. const renderData = {
  2472. tender,
  2473. change: ctx.change,
  2474. changeConst,
  2475. auditConst: audit.changeApply,
  2476. fileList,
  2477. whiteList,
  2478. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply_information),
  2479. preUrl: '/tender/' + ctx.tender.id + '/change/apply/' + ctx.change.id + '/information',
  2480. };
  2481. if ((ctx.change.status === audit.changeApply.status.uncheck || ctx.change.status === audit.changeApply.status.checkNo) && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.tender.isTourist)) {
  2482. // data.accountGroup = accountGroup;
  2483. // 获取所有项目参与者
  2484. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  2485. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  2486. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  2487. });
  2488. renderData.accountList = accountList;
  2489. renderData.accountGroup = accountGroup.map((item, idx) => {
  2490. const groupList = accountList.filter(item => item.account_group === idx);
  2491. return { groupName: item, groupList };
  2492. });
  2493. }
  2494. await this.layout('change/apply_information.ejs', renderData, 'change/apply_information_modal.ejs');
  2495. } catch (err) {
  2496. this.log(err);
  2497. ctx.redirect('/tender/' + ctx.params.id + '/change');
  2498. }
  2499. }
  2500. async applyInformationNotice(ctx) {
  2501. try {
  2502. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  2503. // 获取附件列表
  2504. const fileList = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2505. await this._getChangeApplyAuditViewData(ctx);
  2506. const renderData = {
  2507. tender,
  2508. change: ctx.change,
  2509. changeConst,
  2510. auditConst: audit.changeApply,
  2511. fileList,
  2512. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply_information_notice),
  2513. preUrl: '/tender/' + ctx.tender.id + '/change/apply/' + ctx.change.id + '/information/notice',
  2514. };
  2515. await this.layout('change/apply_information_notice.ejs', renderData, 'change/apply_information_notice_modal.ejs');
  2516. } catch (err) {
  2517. this.log(err);
  2518. ctx.redirect('/tender/' + ctx.params.id + '/change');
  2519. }
  2520. }
  2521. // 审批相关
  2522. /**
  2523. * 添加审批人
  2524. * @param ctx
  2525. * @return {Promise<void>}
  2526. */
  2527. async addApplyAudit(ctx) {
  2528. try {
  2529. const auditConst = audit.changeApply;
  2530. const data = JSON.parse(ctx.request.body.data);
  2531. const id = this.app._.toInteger(data.auditorId);
  2532. if (isNaN(id) || id <= 0) {
  2533. throw '参数错误';
  2534. }
  2535. // 检查权限等
  2536. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2537. throw '您无权添加审核人';
  2538. }
  2539. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2540. throw '当前不允许添加审核人';
  2541. }
  2542. ctx.change.auditorList = await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, ctx.change.times);
  2543. // 检查审核人是否已存在
  2544. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  2545. if (exist) {
  2546. throw '该审核人已存在,请勿重复添加';
  2547. }
  2548. // const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.material, sp_status: shenpiConst.sp_status.gdzs });
  2549. // const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs ? 1 : 0;
  2550. const result = await ctx.service.changeApplyAudit.addAuditor(ctx.change.id, id, ctx.change.times);
  2551. if (!result) {
  2552. throw '添加审核人失败';
  2553. }
  2554. const auditors = await ctx.service.changeApplyAudit.getAuditorsWithOwner(ctx.change.id, ctx.change.times);
  2555. ctx.body = { err: 0, msg: '', data: auditors };
  2556. } catch (err) {
  2557. this.log(err);
  2558. ctx.body = { err: 1, msg: err.toString(), data: null };
  2559. }
  2560. }
  2561. /**
  2562. * 移除审批人
  2563. * @param ctx
  2564. * @return {Promise<void>}
  2565. */
  2566. async deleteApplyAudit(ctx) {
  2567. try {
  2568. const data = JSON.parse(ctx.request.body.data);
  2569. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  2570. if (isNaN(id) || id <= 0) {
  2571. throw '参数错误';
  2572. }
  2573. const result = await ctx.service.changeApplyAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  2574. if (!result) {
  2575. throw '移除审核人失败';
  2576. }
  2577. const auditors = await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, ctx.change.times);
  2578. ctx.body = { err: 0, msg: '', data: auditors };
  2579. } catch (err) {
  2580. ctx.body = { err: 1, msg: err.toString(), data: null };
  2581. }
  2582. }
  2583. /**
  2584. * 上传附件
  2585. * @param {*} ctx 上下文
  2586. */
  2587. async uploadApplyFile(ctx) {
  2588. let stream;
  2589. try {
  2590. const auditConst = audit.changeApply;
  2591. // this._checkAdvanceFileCanModify(ctx);
  2592. const parts = this.ctx.multipart({
  2593. autoFields: true,
  2594. });
  2595. const files = [];
  2596. const create_time = Date.parse(new Date()) / 1000;
  2597. let idx = 0;
  2598. const extra_upload = ctx.change.status === auditConst.status.checked;
  2599. while ((stream = await parts()) !== undefined) {
  2600. if (!stream.filename) {
  2601. // 如果没有传入直接返回
  2602. return;
  2603. }
  2604. const fileInfo = path.parse(stream.filename);
  2605. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_apply/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  2606. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  2607. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  2608. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  2609. ++idx;
  2610. stream && (await sendToWormhole(stream));
  2611. }
  2612. const in_time = new Date();
  2613. const payload = files.map(file => {
  2614. let idx;
  2615. if (Array.isArray(parts.field.name)) {
  2616. idx = parts.field.name.findIndex(name => name === file.name);
  2617. } else {
  2618. idx = 'isString';
  2619. }
  2620. const newFile = {
  2621. tid: ctx.tender.id,
  2622. caid: ctx.change.id,
  2623. uid: ctx.session.sessionUser.accountId,
  2624. type: parts.field.type,
  2625. filename: file.name,
  2626. fileext: file.ext,
  2627. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  2628. filepath: file.filepath,
  2629. upload_time: in_time,
  2630. extra_upload,
  2631. };
  2632. return newFile;
  2633. });
  2634. // 执行文件信息写入数据库
  2635. await ctx.service.changeApplyAtt.saveFileMsgToDb(payload);
  2636. // 将最新的当前标段的所有文件信息返回
  2637. const data = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2638. ctx.body = { err: 0, msg: '', data };
  2639. } catch (err) {
  2640. stream && (await sendToWormhole(stream));
  2641. this.log(err);
  2642. ctx.body = { err: 1, msg: err.toString(), data: null };
  2643. }
  2644. }
  2645. /**
  2646. * 删除附件
  2647. * @param {Ojbect} ctx 上下文
  2648. */
  2649. async deleteApplyFile(ctx) {
  2650. try {
  2651. const { id } = JSON.parse(ctx.request.body.data);
  2652. const fileInfo = await ctx.service.changeApplyAtt.getDataById(id);
  2653. if (fileInfo || Object.keys(fileInfo).length) {
  2654. // 先删除文件
  2655. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  2656. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  2657. // 再删除数据库
  2658. await ctx.service.changeApplyAtt.delete(id);
  2659. } else {
  2660. throw '不存在该文件';
  2661. }
  2662. const data = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  2663. ctx.body = { err: 0, msg: '请求成功', data };
  2664. } catch (err) {
  2665. this.log(err);
  2666. ctx.body = { err: 1, msg: err.toString(), data: null };
  2667. }
  2668. }
  2669. /**
  2670. * 下载附件
  2671. * @param {Object} ctx - egg全局变量
  2672. * @return {void}
  2673. */
  2674. async downloadApplyFile(ctx) {
  2675. const id = ctx.params.fid;
  2676. if (id) {
  2677. try {
  2678. const fileInfo = await ctx.service.changeApplyAtt.getDataById(id);
  2679. if (fileInfo !== undefined && fileInfo !== '') {
  2680. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  2681. // 解决中文无法下载问题
  2682. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  2683. let disposition = '';
  2684. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  2685. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  2686. } else if (userAgent.indexOf('firefox') >= 0) {
  2687. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  2688. } else {
  2689. /* safari等其他非主流浏览器只能自求多福了 */
  2690. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  2691. }
  2692. ctx.response.set({
  2693. 'Content-Type': 'application/octet-stream',
  2694. 'Content-Disposition': disposition,
  2695. 'Content-Length': fileInfo.filesize,
  2696. });
  2697. // ctx.body = await fs.createReadStream(fileName);
  2698. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  2699. } else {
  2700. throw '不存在该文件';
  2701. }
  2702. } catch (err) {
  2703. this.log(err);
  2704. this.setMessage(err.toString(), this.messageType.ERROR);
  2705. }
  2706. }
  2707. }
  2708. async applyInformationSave(ctx) {
  2709. try {
  2710. const data = JSON.parse(ctx.request.body.data);
  2711. if (data.name === 'code') {
  2712. const info = await ctx.service.changeApply.isRepeat(ctx.change.id, data.val, ctx.tender.id);
  2713. if (info) {
  2714. throw '该编号已存在';
  2715. }
  2716. }
  2717. const result = await ctx.service.changeApply.saveInfo(ctx.change.id, data);
  2718. if (!result) {
  2719. throw '修改失败';
  2720. }
  2721. ctx.body = { err: 0, msg: '请求成功', data: null };
  2722. } catch (err) {
  2723. this.log(err);
  2724. ctx.body = { err: 1, msg: err.toString(), data: null };
  2725. }
  2726. }
  2727. /**
  2728. * 上报和重新上报
  2729. * @param ctx
  2730. * @return {Promise<void>}
  2731. */
  2732. async startApplyAudit(ctx) {
  2733. try {
  2734. const auditConst = audit.changeApply;
  2735. // 检查权限等
  2736. if (!ctx.change) {
  2737. throw '数据错误';
  2738. }
  2739. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2740. throw '您无权上报该期数据';
  2741. }
  2742. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2743. throw '该材料调差期数据当前无法上报';
  2744. }
  2745. await ctx.service.changeApplyAudit.start(ctx.change.id, ctx.change.times);
  2746. ctx.redirect(ctx.request.header.referer);
  2747. } catch (err) {
  2748. this.log(err);
  2749. ctx.session.postError = err.toString();
  2750. ctx.redirect(ctx.request.header.referer);
  2751. }
  2752. }
  2753. /**
  2754. * 审批
  2755. * @param ctx
  2756. * @return {Promise<void>}
  2757. */
  2758. async checkApplyAudit(ctx) {
  2759. try {
  2760. const auditConst = audit.changeApply;
  2761. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  2762. throw '当前材料调差期数据有误';
  2763. }
  2764. if (!ctx.change.curAuditor || ctx.change.curAuditor.aid !== ctx.session.sessionUser.accountId) {
  2765. throw '您无权进行该操作';
  2766. }
  2767. const data = {
  2768. checkType: parseInt(ctx.request.body.checkType),
  2769. opinion: ctx.request.body.opinion,
  2770. };
  2771. if (!data.checkType || isNaN(data.checkType)) {
  2772. throw '提交数据错误';
  2773. }
  2774. if (ctx.request.body.notice_uid) {
  2775. data.notice_code = ctx.request.body.notice_code;
  2776. data.notice_uid = ctx.request.body.notice_uid;
  2777. }
  2778. // if (data.checkType === auditConst.status.checkNo) {
  2779. // if (!data.checkType || isNaN(data.checkType)) {
  2780. // throw '提交数据错误';
  2781. // }
  2782. // }
  2783. await ctx.service.changeApplyAudit.check(ctx.change.id, data, ctx.change.times);
  2784. ctx.redirect(ctx.request.header.referer);
  2785. } catch (err) {
  2786. this.log(err);
  2787. ctx.session.postError = err.toString();
  2788. ctx.redirect(ctx.request.header.referer);
  2789. }
  2790. }
  2791. }
  2792. return ChangeController;
  2793. };