change_controller.js 224 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574
  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 auditType = require('../const/audit').auditType;
  22. const accountGroup = require('../const/account_group').group;
  23. const shenpiConst = require('../const/shenpi');
  24. const tenderMenu = require('../../config/menu').tenderMenu;
  25. const measureType = require('../const/tender').measureType;
  26. const spreadConst = require('../const/spread');
  27. const stdConst = require('../const/standard');
  28. // const tenderMenu = require('../../config/menu').tenderMenu;
  29. const spreadSetting = require('../lib/spread_setting');
  30. module.exports = app => {
  31. class ChangeController extends app.BaseController {
  32. /**
  33. * 构造函数
  34. *
  35. * @param {Object} ctx - egg全局变量
  36. * @return {void}
  37. */
  38. constructor(ctx) {
  39. super(ctx);
  40. ctx.showProject = true;
  41. ctx.showTender = true;
  42. ctx.showTitle = true;
  43. }
  44. async _filterChanges(ctx, status = 0) {
  45. const tenderId = ctx.params.id;
  46. ctx.session.sessionUser.tenderId = tenderId;
  47. const tender = await this.service.tender.getDataById(tenderId);
  48. // const tenderList = await this.service.tender.getList();
  49. const page = ctx.page;
  50. const pageSize = ctx.pageSize;
  51. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  52. const orders = ctx.query.order ? ctx.query.order : 0;
  53. const state = ctx.subProject.page_show.openChangeState && ctx.query.state ? parseInt(ctx.query.state) : 0;
  54. const changes = await ctx.service.change.getListByStatus(tender.id, status, 1, sorts, orders, state);
  55. const total = await ctx.service.change.getCountByStatus(tender.id, status, state);
  56. let page_total = 0;
  57. const tp = await ctx.service.change.getTp(tender.id, status, state);
  58. if (changes !== null) {
  59. for (const c of changes) {
  60. if (c.status !== audit.change.status.checked || !c.final_auditor_str) {
  61. c.curAuditors = await ctx.service.changeAudit.getAuditorsByStatus(c.cid, c.status, c.times);
  62. if (c.status === audit.change.status.checkNoPre) {
  63. c.curAuditors2 = await ctx.service.stageAudit.getAuditorsByStatus(c.cid, audit.change.status.checking, c.times);
  64. }
  65. if (c.status === audit.change.status.checkNo || c.status === audit.change.status.revise) {
  66. const changeUsedData = await ctx.service.stageChange.getAllFinalUsedData(ctx.tender.id, c.cid);
  67. c.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.qty); }));
  68. c.isSettle = await ctx.service.changeSettleList.isSettle(c.cid);
  69. }
  70. if (c.status === audit.change.status.checked && c.curAuditors.length > 0) {
  71. const final_auditor_str = c.curAuditors[0].audit_type === auditType.key.common
  72. ? c.curAuditors[0].name + (c.curAuditors[0].role ? '-' + c.curAuditors[0].role : '')
  73. : ctx.helper.transFormToChinese(c.curAuditors[0].audit_order) + '审';
  74. await ctx.service.change.defaultUpdate({ final_auditor_str }, { where: { cid: c.cid } });
  75. }
  76. }
  77. const user = await ctx.service.projectAccount.getDataById(c.uid);
  78. c.username = user ? user.name : '';
  79. page_total = ctx.helper.add(page_total, c.total_price);
  80. }
  81. }
  82. // 分页相关
  83. const pageInfo = {
  84. page,
  85. pageSizeSelect: 1,
  86. pageSize,
  87. total_num: total,
  88. total: Math.ceil(total / pageSize),
  89. queryData: JSON.stringify(ctx.urlInfo.query),
  90. };
  91. const filter = JSON.parse(JSON.stringify(audit.filter));
  92. filter.count = [];
  93. 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);
  94. 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);
  95. 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);
  96. 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);
  97. 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);
  98. const codeRule = tender.c_rule ? JSON.parse(tender.c_rule) : [];
  99. for (const rule of codeRule) {
  100. switch (rule.rule_type) {
  101. case codeRuleConst.measure.ruleType.dealCode:
  102. rule.preview = ctx.tender.info.deal_info.dealCode;
  103. break;
  104. case codeRuleConst.measure.ruleType.tenderName:
  105. rule.preview = tender.name;
  106. break;
  107. case codeRuleConst.measure.ruleType.inDate:
  108. rule.preview = moment().format('YYYY');
  109. break;
  110. case codeRuleConst.measure.ruleType.text:
  111. rule.preview = rule.text;
  112. break;
  113. case codeRuleConst.measure.ruleType.addNo:
  114. const s = '0000000000';
  115. rule.preview = s.substr(s.length - rule.format);
  116. break;
  117. default: break;
  118. }
  119. }
  120. const changePlanList = await ctx.service.changePlan.getAllDataByCondition({ where: { tid: tender.id, status: audit.changePlan.status.checked } });
  121. const allPlanCodes = await ctx.service.change.getAllDataByCondition({
  122. columns: ['plan_code'],
  123. where: {
  124. tid: tender.id,
  125. },
  126. });
  127. const apLists = allPlanCodes.length > 0 ? ctx.app._.uniq(ctx.app._.map(allPlanCodes, 'plan_code')) : [];
  128. const need_checking = await ctx.service.change.getCheckingList(ctx.tender.id, ctx.session.sessionUser.accountId, true);
  129. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  130. const userPermission = pa && pa.permission ? JSON.parse(pa.permission) : null;
  131. const addPermission = !!(userPermission && userPermission.change !== undefined && userPermission.change.indexOf('3') !== -1);
  132. const renderData = {
  133. moment,
  134. tender,
  135. // tenderList,
  136. pageInfo,
  137. changes,
  138. page_total,
  139. tp,
  140. filter,
  141. status,
  142. codeRule,
  143. dealCode: ctx.tender.info.deal_info.dealCode,
  144. auditConst: audit.change,
  145. changeConst,
  146. shenpiConst,
  147. state,
  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. changePlanList,
  154. apLists,
  155. auditType,
  156. precision: ctx.tender.info.precision,
  157. need_checking,
  158. addPermission,
  159. };
  160. if (ctx.subProject.page_show.openChangeState) {
  161. // 工程变更类别读取
  162. const fun_set = this.ctx.subProject.fun_set;
  163. const changeState = fun_set.change_state;
  164. for (const cs of changeState) {
  165. cs.count = await ctx.service.change.getCountByStatus(tender.id, status, cs.order);
  166. }
  167. renderData.changeState = changeState;
  168. }
  169. await this.layout('change/index.ejs', renderData, 'change/modal.ejs');
  170. }
  171. /**
  172. * 变更管理 页面 (Get)
  173. *
  174. * @param {Object} ctx - egg全局变量
  175. * @return {void}
  176. */
  177. async index(ctx) {
  178. try {
  179. await this._filterChanges(ctx);
  180. } catch (err) {
  181. this.log(err);
  182. ctx.redirect('/dashboard');
  183. }
  184. }
  185. /**
  186. * 审批流程(Get)
  187. * @param ctx
  188. * @return {Promise<void>}
  189. */
  190. async changeAuditors(ctx) {
  191. try {
  192. const cid = JSON.parse(ctx.request.body.data).cid;
  193. const tenderId = ctx.params.id;
  194. const changeInfo = await ctx.service.change.getDataByCondition({ cid });
  195. await ctx.service.change.loadChangeUser(changeInfo);
  196. await ctx.service.change.loadChangeAuditViewData(changeInfo);
  197. ctx.body = { err: 0, msg: '', data: changeInfo };
  198. } catch (error) {
  199. this.log(error);
  200. ctx.body = { err: 1, msg: error.toString(), data: null };
  201. }
  202. }
  203. /**
  204. *
  205. * @param {Object} ctx - egg全局变量
  206. * @return {void}
  207. */
  208. async newCode(ctx) {
  209. const responseData = {
  210. err: 0,
  211. msg: '',
  212. data: '',
  213. };
  214. try {
  215. const tenderId = ctx.params.id;
  216. if (!tenderId) {
  217. throw '当前未打开标段';
  218. }
  219. const tenderData = await ctx.service.tender.getDataById(tenderId);
  220. const data = JSON.parse(ctx.request.body.data);
  221. let cCodeRule;
  222. let cConnector;
  223. let changeCount = 0;
  224. if (data && data.type) {
  225. const c_code_rules = tenderData.c_code_rules !== null ? JSON.parse(tenderData.c_code_rules) : null;
  226. cCodeRule = c_code_rules && c_code_rules[data.type + '_rule'] ? c_code_rules[data.type + '_rule'] : [];
  227. cConnector = c_code_rules && c_code_rules[data.type + '_connector'] ? c_code_rules[data.type + '_connector'] : null;
  228. if (data.type === codeRuleConst.ruleField[codeRuleConst.ruleType.apply]) {
  229. changeCount = await ctx.service.changeApply.count({ tid: tenderId });
  230. } else if (data.type === codeRuleConst.ruleField[codeRuleConst.ruleType.plan]) {
  231. changeCount = await ctx.service.changePlan.count({ tid: tenderId });
  232. } else {
  233. changeCount = await ctx.service.changeProject.count({ tid: tenderId, type: codeRuleConst.ruleType[data.type] });
  234. }
  235. } else {
  236. cCodeRule = tenderData.c_rule !== null ? JSON.parse(tenderData.c_rule) : [];
  237. cConnector = tenderData.c_connector;
  238. changeCount = await ctx.service.change.count({ tid: tenderId });
  239. }
  240. const code = [];
  241. for (const rule of cCodeRule) {
  242. switch (rule.rule_type) {
  243. case codeRuleConst.measure.ruleType.dealCode:
  244. code.push(ctx.tender.info.deal_info.dealCode);
  245. break;
  246. case codeRuleConst.measure.ruleType.tenderName:
  247. code.push(tenderData.name);
  248. break;
  249. case codeRuleConst.measure.ruleType.text:
  250. code.push(rule.text);
  251. break;
  252. case codeRuleConst.measure.ruleType.inDate:
  253. code.push(moment().format('YYYY'));
  254. break;
  255. case codeRuleConst.measure.ruleType.addNo:
  256. let s = '0000000000';
  257. const count = rule.start + changeCount;
  258. s = s + count;
  259. code.push(s.substr(s.length - rule.format));
  260. break;
  261. default: break;
  262. }
  263. }
  264. responseData.data = code.join(cConnector !== null && parseInt(cConnector) !== 3 ? codeRuleConst.measure.connectorString[cConnector] : '');
  265. } catch (err) {
  266. responseData.err = 1;
  267. responseData.msg = err;
  268. }
  269. ctx.body = responseData;
  270. }
  271. /**
  272. * 新增变更 (Post)
  273. *
  274. * @param {Object} ctx - egg全局变量
  275. * @return {void}
  276. */
  277. async add(ctx) {
  278. try {
  279. const tenderId = ctx.params.id;
  280. if (!tenderId) {
  281. throw '当前未打开标段';
  282. }
  283. const data = JSON.parse(ctx.request.body.data);
  284. if (!data.code || data.code === '') {
  285. throw '变更令号不能为空';
  286. }
  287. const fun_set = this.ctx.subProject.fun_set;
  288. const stateInfo = ctx.helper._.find(fun_set.change_state, { order: 3 });
  289. // 在生成新变更令后,需要copy前一个变更令报表的签名信息
  290. const lastChange = await ctx.service.change.getLastChange(tenderId);
  291. const change = await ctx.service.change.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.plan_code, data.name, data.add_plan_list, stateInfo.value);
  292. await ctx.service.roleRptRel.createRoleRelationshipFromOtherBz(tenderId, '-300', change.cid, lastChange ? lastChange.cid : null);
  293. ctx.body = { err: 0, msg: '', data: change };
  294. } catch (err) {
  295. this.log(err);
  296. ctx.body = { err: 1, msg: err.toString() };
  297. }
  298. }
  299. /**
  300. * 变更管理 状态筛选 页面 (Get)
  301. * @param {Object} ctx - egg全局变量
  302. * @return {void}
  303. */
  304. async status(ctx) {
  305. try {
  306. const status = parseInt(ctx.params.status);
  307. await this._filterChanges(ctx, status);
  308. } catch (err) {
  309. this.logger.error(err);
  310. ctx.redirect('/tender/' + ctx.params.id + '/change');
  311. }
  312. }
  313. async batchChangeFun(ctx) {
  314. try {
  315. const data = JSON.parse(ctx.request.body.data);
  316. const responseData = {
  317. err: 0,
  318. msg: '',
  319. data: {},
  320. };
  321. switch (data.type) {
  322. case 'get_report_list':
  323. responseData.data.shenpi_status = ctx.tender.info.shenpi.change;
  324. responseData.data.uncheckList = await ctx.service.change.getUncheckList(ctx.tender.id, ctx.tender.info.shenpi.change);
  325. if (ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  326. responseData.data.spGroupList = await ctx.service.shenpiGroup.getGroupListByChangeType(ctx.tender.id, shenpiConst.sp_type.change, 'change');
  327. } else {
  328. // 获取所有项目参与者
  329. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  330. responseData.data.accountList = accountList;
  331. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  332. responseData.data.accountGroup = unitList.map(item => {
  333. const groupList = accountList.filter(item1 => item1.company === item.name);
  334. return { groupName: item.name, groupList };
  335. }).filter(x => { return x.groupList.length > 0; });
  336. }
  337. break;
  338. case 'get_shenpi_list':
  339. responseData.data.checkingList = await ctx.service.change.getCheckingList(ctx.tender.id, ctx.session.sessionUser.accountId);
  340. break;
  341. case 'set_shenpi_list':
  342. await ctx.service.changeAudit.batchSetAudits(ctx.tender.id, data.cids, data.from_cid);
  343. responseData.data.uncheckList = await ctx.service.change.getUncheckList(ctx.tender.id, ctx.tender.info.shenpi.change);
  344. break;
  345. default: throw '参数有误';
  346. }
  347. ctx.body = responseData;
  348. } catch (err) {
  349. this.log(err);
  350. ctx.body = { err: 1, msg: err.toString(), data: null };
  351. }
  352. }
  353. /**
  354. * 获取审批界面所需的 原报、审批人数据等
  355. * @param ctx
  356. * @return {Promise<void>}
  357. * @private
  358. */
  359. async _getChangeAuditViewData(ctx) {
  360. await ctx.service.change.loadChangeAuditViewData(ctx.change);
  361. // await this._checkStageStart(ctx);
  362. }
  363. /**
  364. * 变更信息 新版本页面 (Get)
  365. *
  366. * @param {Object} ctx - egg全局变量
  367. * @return {void}
  368. */
  369. async information(ctx) {
  370. try {
  371. const whiteList = this.ctx.app.config.multipart.whitelist;
  372. await this._getChangeAuditViewData(ctx);
  373. const tender = ctx.tender;
  374. const tenderData = await ctx.service.tender.getDataById(tender.id);
  375. const change = ctx.change;
  376. // 获取附件列表
  377. const attList = await ctx.service.changeAtt.getChangeAttachment(change.cid, 'desc');
  378. // 获取其他变更令数据
  379. const othersChange = await ctx.service.change.getOthersChange(ctx.tender.id, change.cid);
  380. // 获取变更方案的清单
  381. let planList = [];
  382. let showPlanBtn = false;
  383. if (ctx.subProject.page_show.openChangePlan) {
  384. const planInfo = change.plan_code ? await ctx.service.changePlan.getDataByCondition({ tid: tender.id, code: change.plan_code }) : null;
  385. showPlanBtn = change.plan_code !== null && change.plan_code !== '';
  386. if (planInfo && planInfo.id) {
  387. planList = await ctx.service.changePlanList.getAllDataByCondition({ where: { cpid: planInfo.id } });
  388. }
  389. }
  390. // 获取清单
  391. const changeList = await ctx.service.changeAuditList.getList(change.cid);
  392. if (change.status === audit.change.status.checked || change.status === audit.change.status.checking || change.status === audit.change.status.checkNoPre) {
  393. for (const cl of changeList) {
  394. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  395. // 清单表页赋值
  396. for (const au in change.userGroups) {
  397. if (change.userGroups[au][0].audit_order !== 0) {
  398. cl['audit_amount_' + change.userGroups[au][0].audit_order] =
  399. (change.userGroups[au][0].audit_type === auditType.key.and &&
  400. ctx.helper._.findIndex(change.userGroups[au], { status: audit.change.status.checking }) !== -1 &&
  401. ctx.helper._.findIndex(change.userGroups[au], { uid: ctx.session.sessionUser.accountId, status: audit.change.status.checked }) !== -1) ||
  402. (change.shenpiPower && ctx.helper._.findIndex(change.userGroups[au], { uid: ctx.session.sessionUser.accountId }) !== -1) ?
  403. cl.spamount : (audit_amount[au - 1] !== undefined ? parseFloat(audit_amount[au - 1]) : null);
  404. }
  405. }
  406. if (change.readOnly && !change.shenpiPower) {
  407. cl.checked_amount = audit_amount.length > 0 ? parseFloat(audit_amount[audit_amount.length - 1]) : cl.camount;
  408. }
  409. }
  410. }
  411. // 工程变更类别读取
  412. const fun_set = this.ctx.subProject.fun_set;
  413. // 获取用户人验证手机号
  414. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  415. const auth_mobile = pa.auth_mobile;
  416. const userPermission = pa && pa.permission ? JSON.parse(pa.permission) : null;
  417. const deleteFilePermission = !!(userPermission && userPermission.change !== undefined && userPermission.change.indexOf('2') !== -1);
  418. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  419. const settleBills = ctx.change.readySettle ? await ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: ctx.change.readySettle.id } }) : [];
  420. const settlePos = ctx.change.readySettle ? await ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: ctx.change.readySettle.id } }) : [];
  421. // 判断并是否更新结算清单数据
  422. await ctx.service.change.checkSettleUpdate(ctx.tender.id, ctx.change.readySettle);
  423. // 处理清单数据
  424. const removeSettleNum = change.status !== audit.change.status.checked ? await ctx.service.changeSettleList.updateChangeList(change.cid, settleBills, settlePos, changeList) : 0;
  425. const renderData = {
  426. tender,
  427. change,
  428. othersChange,
  429. changeConst,
  430. changeClass: fun_set.change_class,
  431. changeState: fun_set.change_state,
  432. auditConst: audit.change,
  433. ledgerConsts: audit.ledger.status,
  434. auditType,
  435. auditorGroups: change.userGroups,
  436. attList,
  437. whiteList,
  438. showPlanBtn,
  439. planList,
  440. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  441. upUnit: change.up_decimal ? change.up_decimal : ctx.tender.info.decimal.up,
  442. authMobile: auth_mobile,
  443. shenpiConst,
  444. settleStatus: ctx.service.settle.settleStatus,
  445. unitList,
  446. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.information),
  447. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  448. precision: ctx.tender.info.precision,
  449. settleBills,
  450. settlePos,
  451. removeSettleNum,
  452. deleteFilePermission,
  453. changeMode: tenderData.c_mode,
  454. };
  455. // 获取是否已存在调用变更令
  456. let changeUsedData = await ctx.service.stageChange.getAllFinalUsedData(ctx.tender.id, change.cid);
  457. changeUsedData = ctx.helper._.orderBy(ctx.helper._.filter(changeUsedData, function(item) {
  458. return item.qty !== null;
  459. }), ['sorder'], ['desc']);
  460. const useChangeUsedData = [];
  461. if (changeUsedData.length > 0) { // 防止未创建期时调用
  462. for (const cu of changeUsedData) {
  463. const index = ctx.helper._.findIndex(useChangeUsedData, { cbid: cu.cbid });
  464. if (index !== -1) {
  465. useChangeUsedData[index].qty = ctx.helper.add(useChangeUsedData[index].qty, cu.qty);
  466. } else {
  467. useChangeUsedData.push(cu);
  468. }
  469. }
  470. }
  471. renderData.changeUsedData = useChangeUsedData;
  472. renderData.stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.qty); }));
  473. renderData.changeLedgerList = await ctx.service.changeLedger.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  474. renderData.changePosList = await ctx.service.changePos.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  475. renderData.changeUnits = changeConst.units;
  476. if (!change.readOnly || change.shenpiPower) {
  477. // 获取公司列表
  478. const companyList = await ctx.service.changeCompany.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  479. renderData.companyList = companyList;
  480. }
  481. if (!change.readOnly || ctx.session.sessionUser.is_admin) {
  482. // 获取所有项目参与者
  483. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  484. renderData.accountList = accountList;
  485. renderData.accountGroup = unitList.map(item => {
  486. const groupList = accountList.filter(item1 => item1.company === item.name);
  487. return { groupName: item.name, groupList };
  488. }).filter(x => { return x.groupList.length > 0; });
  489. const stateInfo = ctx.helper._.find(fun_set.change_state, { order: ctx.change.state });
  490. renderData.deLimit = stateInfo.value;
  491. if (!change.readOnly) {
  492. if (stateInfo.value !== ctx.change.delimit) {
  493. // 需要更新所有的计量上限值,除了已调用的值
  494. const updateList = [];
  495. for (const cl of changeList) {
  496. const one = {
  497. id: cl.id,
  498. };
  499. if (useChangeUsedData.length > 0 && ctx.helper._.findIndex(useChangeUsedData, { cbid: cl.id }) !== -1) {
  500. // 获取比例值
  501. const uc = ctx.helper._.find(useChangeUsedData, { cbid: cl.id });
  502. const minLimit = Math.ceil(ctx.helper.mul(ctx.helper.div(uc.qty, cl.camount), 100));
  503. if (minLimit <= renderData.deLimit) {
  504. one.delimit = renderData.deLimit;
  505. cl.delimit = renderData.deLimit;
  506. }
  507. } else if (cl.delimit !== renderData.deLimit) {
  508. one.delimit = renderData.deLimit;
  509. cl.delimit = renderData.deLimit;
  510. }
  511. if (!ctx.helper._.isEqual(one, { id: cl.id })) updateList.push(one);
  512. }
  513. console.log(updateList);
  514. if (updateList.length > 0) await ctx.service.changeAuditList.defaultUpdateRows(updateList);
  515. await ctx.service.change.defaultUpdate({ delimit: stateInfo.value }, { where: { cid: change.cid } });
  516. }
  517. // 判断是否更新变更类别
  518. if (ctx.helper._.findIndex(fun_set.change_class, { value: change.class, checked: true }) === -1) {
  519. renderData.change.class = ctx.helper._.find(fun_set.change_class, { checked: true }).value;
  520. await ctx.service.change.saveInfo({ class: ctx.helper._.find(fun_set.change_class, { checked: true }).value });
  521. }
  522. // 获取固定审批流列表
  523. if (tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  524. renderData.spGroupList = await ctx.service.shenpiGroup.getGroupListByChangeType(tender.id, shenpiConst.sp_type.change, 'change');
  525. }
  526. }
  527. }
  528. renderData.changeList = changeList;
  529. await this.layout('change/information.ejs', renderData, 'change/information_modal.ejs');
  530. } catch (err) {
  531. this.log(err);
  532. ctx.session.postError = err.toString();
  533. ctx.redirect('/tender/' + ctx.params.id + '/change');
  534. }
  535. }
  536. /**
  537. * 变更关联数据 - 操作 (Ajax)
  538. * @param ctx
  539. * @return {Promise<void>}
  540. */
  541. async relation(ctx) {
  542. try {
  543. if (!ctx.subProject.page_show.openChangePlan) {
  544. throw '该功能已关闭';
  545. }
  546. // await this._getChangeAuditViewData(ctx);
  547. const tender = ctx.tender;
  548. const change = ctx.change;
  549. const renderData = {
  550. tender,
  551. change,
  552. };
  553. renderData.changePlanInfo = null;
  554. renderData.changeApplyInfo = null;
  555. renderData.changeProjectInfo = null;
  556. if (change.plan_code) {
  557. renderData.changePlanInfo = await ctx.service.changePlan.getDataByCondition({ tid: tender.id, code: change.plan_code });
  558. if (renderData.changePlanInfo && renderData.changePlanInfo.apply_code) {
  559. renderData.changeApplyInfo = await ctx.service.changeApply.getDataByCondition({ tid: tender.id, code: renderData.changePlanInfo.apply_code });
  560. if (renderData.changeApplyInfo && renderData.changeApplyInfo.project_code) {
  561. renderData.changeProjectInfo = await ctx.service.changeProject.getDataByCondition({ tid: tender.id, code: renderData.changeApplyInfo.project_code });
  562. }
  563. }
  564. }
  565. await this.layout('change/relation.ejs', renderData);
  566. } catch (err) {
  567. this.log(err);
  568. ctx.session.postError = err.toString();
  569. ctx.redirect('/tender/' + ctx.params.id + '/change');
  570. }
  571. }
  572. /**
  573. * 变更清单 - 操作 (Ajax)
  574. * @param ctx
  575. * @return {Promise<void>}
  576. */
  577. async saveListsData(ctx) {
  578. try {
  579. const data = JSON.parse(ctx.request.body.data);
  580. const responseData = {
  581. err: 0,
  582. msg: '',
  583. data: {},
  584. };
  585. switch (data.type) {
  586. case 'add':
  587. case 'batchadd':
  588. if (!ctx.subProject.page_show.openChangeWhiteList) {
  589. throw '空白清单添加功能未开启。';
  590. }
  591. const fun_set = this.ctx.subProject.fun_set;
  592. const stateInfo = ctx.helper._.find(fun_set.change_state, { order: ctx.change.state });
  593. if (data.type === 'add') {
  594. responseData.data = await ctx.service.changeAuditList.add(data.postData, stateInfo.value);
  595. } else {
  596. responseData.data = await ctx.service.changeAuditList.batchAdd(data, stateInfo.value);
  597. }
  598. break;
  599. case 'del':
  600. await ctx.service.changeAuditList.del(data);
  601. break;
  602. case 'update':
  603. await ctx.service.changeAuditList.save(data.updateData);
  604. break;
  605. case 'paste':
  606. if (ctx.change.status !== audit.change.status.uncheck && ctx.change.status !== audit.change.status.checkNo && ctx.change.status !== audit.change.status.revise) {
  607. throw '该变更令正在审批中或已完成,无法操作清单数据';
  608. }
  609. if (data.insertData && data.insertData.length > 0) {
  610. const fun_set2 = this.ctx.subProject.fun_set;
  611. const stateInfo2 = ctx.helper._.find(fun_set2.change_state, { order: ctx.change.state });
  612. await ctx.service.changeAuditList.adds(data.insertData, stateInfo2.value);
  613. }
  614. if (data.updateData && data.updateData.length > 0) {
  615. await ctx.service.changeAuditList.saveDatas(data.updateData);
  616. }
  617. // 取所有工料表
  618. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  619. break;
  620. case 'ledger_list':
  621. await ctx.service.changeAuditList.saveLedgerListDatas(data.updateData, data.postData);
  622. // 取所有工料表
  623. responseData.data = { changeList: await ctx.service.changeAuditList.getList(ctx.change.cid),
  624. usedList: await ctx.service.stageChange.getAllFinalUsedData(ctx.tender.id, ctx.change.cid) };
  625. break;
  626. case 'remove_list':
  627. await ctx.service.changeAuditList.removeLedgerListDatas(data.updateData);
  628. // 取所有工料表
  629. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  630. break;
  631. case 'update_list':
  632. await ctx.service.changeAuditList.saveDatas(data.updateData);
  633. // 取所有工料表
  634. // responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  635. break;
  636. case 'info':
  637. let value = 100;
  638. if (data.updateData.state && parseInt(data.updateData.state) !== ctx.change.state) {
  639. const fun_set = this.ctx.subProject.fun_set;
  640. const stateInfo = ctx.helper._.find(fun_set.change_state, { order: parseInt(data.updateData.state) });
  641. value = stateInfo.value;
  642. }
  643. responseData.data = await ctx.service.change.saveInfo(data.updateData, value);
  644. // 取所有工料表
  645. // responseData.data = '保存成功';
  646. break;
  647. case 'paste_amount_rows':
  648. await ctx.service.changeAuditList.saveDatas(data.updateData);
  649. const changeList = await ctx.service.changeAuditList.getList(ctx.change.cid);
  650. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times);
  651. // changeList = JSON.parse(JSON.stringify(changeList.sort())).sort().sort();
  652. // for (const cl of changeList) {
  653. // const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  654. // // 清单表页赋值
  655. // for (const [index, au] of auditList2.entries()) {
  656. // if (au.usite !== 0) {
  657. // cl['audit_amount_' + au.uid] = au.uid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index - 1] ? audit_amount[index - 1] : null);
  658. // }
  659. // }
  660. // }
  661. for (const cl of changeList) {
  662. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  663. // 清单表页赋值
  664. for (const au in ctx.change.userGroups) {
  665. if (ctx.change.userGroups[au][0].audit_order !== 0) {
  666. cl['audit_amount_' + ctx.change.userGroups[au][0].audit_order] =
  667. (ctx.change.userGroups[au][0].audit_type === auditType.key.and &&
  668. ctx.helper._.findIndex(ctx.change.userGroups[au], { status: audit.change.status.checking }) !== -1 &&
  669. ctx.helper._.findIndex(ctx.change.userGroups[au], { uid: ctx.session.sessionUser.accountId, status: audit.change.status.checked }) !== -1) ||
  670. (ctx.change.shenpiPower && ctx.helper._.findIndex(ctx.change.userGroups[au], { uid: ctx.session.sessionUser.accountId }) !== -1) ?
  671. cl.spamount : (audit_amount[au - 1] !== undefined ? parseFloat(audit_amount[au - 1]) : null);
  672. }
  673. }
  674. }
  675. // 取所有工料表
  676. responseData.data = changeList;
  677. break;
  678. case 'update_tp':
  679. await ctx.service.change.saveInfo(data.updateData);
  680. break;
  681. case 'order_by':
  682. const result = await ctx.service.change.saveOrderBy(data.updateData, data.updateOrderList);
  683. responseData.data = result;
  684. break;
  685. case 'order_site':
  686. await ctx.service.change.defaultUpdate({ order_site: data.listid }, { where: { cid: ctx.change.cid } });
  687. break;
  688. case 'changeOrder':
  689. await ctx.service.changeAuditList.changeOrder(data.postData);
  690. break;
  691. case 'set_all_valuation':
  692. await ctx.service.changeAuditList.setAllValuation(ctx.change.cid, data.ids, data.is_valuation);
  693. // 取所有工料表
  694. responseData.data = await ctx.service.changeAuditList.getList(ctx.change.cid);
  695. break;
  696. // 从新增部位页新增清单
  697. case 'add-change-list':
  698. if (ctx.change.status !== audit.change.status.uncheck && ctx.change.status !== audit.change.status.checkNo && ctx.change.status !== audit.change.status.revise) {
  699. throw '该变更令正在审批中或已完成,无法操作清单数据';
  700. }
  701. const fun_set2 = this.ctx.subProject.fun_set;
  702. const stateInfo2 = ctx.helper._.find(fun_set2.change_state, { order: ctx.change.state });
  703. await ctx.service.changeAuditList.adds(data.postData, stateInfo2.value);
  704. responseData.data = { changeList: await ctx.service.changeAuditList.getList(ctx.change.cid) };
  705. break;
  706. // 从新增部位页删除清单
  707. case 'del-change-list':
  708. if (ctx.change.status !== audit.change.status.uncheck && ctx.change.status !== audit.change.status.checkNo && ctx.change.status !== audit.change.status.revise) {
  709. throw '该变更令正在审批中或已完成,无法操作清单数据';
  710. }
  711. await ctx.service.changeAuditList.dels(data);
  712. responseData.data = { changeList: await ctx.service.changeAuditList.getList(ctx.change.cid) };
  713. break;
  714. case 'get-revise-list':
  715. responseData.data.changeLedgerList = await ctx.service.changeLedger.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  716. responseData.data.changePosList = await ctx.service.changePos.getAllDataByCondition({ where: { tid: ctx.tender.id } });
  717. break;
  718. case 'plan_code':
  719. responseData.data.planInfo = null;
  720. responseData.data.applyInfo = null;
  721. responseData.data.projectInfo = null;
  722. await ctx.service.change.defaultUpdate({ plan_code: data.plan_code }, { where: { cid: ctx.change.cid } });
  723. if (data.plan_code) {
  724. responseData.data.planInfo = await ctx.service.changePlan.getDataByCondition({ tid: ctx.tender.id, code: data.plan_code });
  725. if (responseData.data.planInfo && responseData.data.planInfo.apply_code) {
  726. responseData.data.applyInfo = await ctx.service.changeApply.getDataByCondition({ tid: ctx.tender.id, code: responseData.data.planInfo.apply_code });
  727. if (responseData.data.applyInfo && responseData.data.applyInfo.project_code) {
  728. responseData.data.projectInfo = await ctx.service.changeProject.getDataByCondition({ tid: ctx.tender.id, code: responseData.data.applyInfo.project_code });
  729. }
  730. }
  731. }
  732. break;
  733. case 'change_mode':
  734. await ctx.service.tender.defaultUpdate({
  735. id: ctx.tender.id,
  736. c_mode: data.updateData ? 1 : 0,
  737. });
  738. const changeList2 = await ctx.service.changeAuditList.getList(ctx.change.cid);
  739. if (ctx.change.readOnly) {
  740. const auditList2 = await ctx.service.changeAudit.getListGroupByTimes(ctx.change.cid, ctx.change.times);
  741. for (const cl of changeList2) {
  742. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  743. // 清单表页赋值
  744. for (const au in ctx.change.userGroups) {
  745. if (ctx.change.userGroups[au][0].audit_order !== 0) {
  746. cl['audit_amount_' + ctx.change.userGroups[au][0].audit_order] =
  747. (ctx.change.userGroups[au][0].audit_type === auditType.key.and &&
  748. ctx.helper._.findIndex(ctx.change.userGroups[au], { status: audit.change.status.checking }) !== -1 &&
  749. ctx.helper._.findIndex(ctx.change.userGroups[au], { uid: ctx.session.sessionUser.accountId, status: audit.change.status.checked }) !== -1) ||
  750. (ctx.change.shenpiPower && ctx.helper._.findIndex(ctx.change.userGroups[au], { uid: ctx.session.sessionUser.accountId }) !== -1) ?
  751. cl.spamount : (audit_amount[au - 1] !== undefined ? parseFloat(audit_amount[au - 1]) : null);
  752. }
  753. }
  754. }
  755. }
  756. // 取所有工料表
  757. responseData.data = changeList2;
  758. break;
  759. default: throw '参数有误';
  760. }
  761. ctx.body = responseData;
  762. } catch (err) {
  763. this.log(err);
  764. ctx.body = { err: 1, msg: err.toString(), data: null };
  765. }
  766. }
  767. /**
  768. * 上报和重新上报
  769. * @param ctx
  770. * @return {Promise<void>}
  771. */
  772. async startAudit(ctx) {
  773. const responseData = {
  774. err: 0,
  775. msg: '',
  776. data: {},
  777. };
  778. try {
  779. // 检查权限等
  780. if (!ctx.change) {
  781. throw '数据错误';
  782. }
  783. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  784. throw '您无权上报该变更令数据';
  785. }
  786. if (!(ctx.change.status === audit.change.status.uncheck || ctx.change.status === audit.change.status.checkNo || ctx.change.status === audit.change.status.revise)) {
  787. throw '该变更令当前无法上报';
  788. }
  789. // 判断是否是修订,判断有无审批人员作弊
  790. if ((ctx.change.status === audit.change.status.revise || ctx.change.is_revise) && ctx.tender.info.shenpi.change === shenpiConst.sp_status.sqspr) {
  791. // 获取上一次的审批人流程
  792. const lastUserList = await ctx.service.changeAudit.getUniqAuditor(ctx.change.cid, ctx.change.times - 1);
  793. const lastUidList = ctx.helper._.map(lastUserList, 'uid');
  794. // 判断上一次审批是否为非原报为审批人
  795. const nowUidList = ctx.helper._.map(ctx.change.auditors, 'uid');
  796. // 判断条件修订可上报条件
  797. // 1.有原报,不管有无其他人 可以添加原报作为审核人,但是不能只原报上报
  798. // 2.无原报,有其他人 不可以添加原报
  799. // const noYBUidList = ctx.change.status === audit.change.status.revise ? ctx.helper._.initial(ctx.helper._.tail(lastUidList)) : ctx.helper._.tail(lastUidList);
  800. const noYBUidList = ctx.helper._.tail(lastUidList);
  801. // if (!ctx.helper._.isEqual(lastUidList, nowUidList) && ctx.helper._.includes(noYBUidList, lastUidList[0]) && nowUidList.length === 2 && nowUidList[0] === nowUidList[1]) {
  802. if (nowUidList.length === 2 && nowUidList[0] === nowUidList[1]) {
  803. throw '该变更令不能指定原报人为单独审批人';
  804. }
  805. if (!ctx.helper._.isEqual(lastUidList, nowUidList) && !ctx.helper._.includes(noYBUidList, lastUidList[0]) && ctx.helper._.includes(ctx.helper._.tail(nowUidList), nowUidList[0])) {
  806. throw '该变更令不能指定原报为审批人,请移除';
  807. }
  808. }
  809. await ctx.service.changeAudit.start(ctx.change.cid, ctx.change.times);
  810. // ctx.redirect(ctx.request.header.referer);
  811. ctx.body = responseData;
  812. } catch (err) {
  813. this.log(err);
  814. // ctx.session.postError = err.toString();
  815. // ctx.redirect(ctx.request.header.referer);
  816. ctx.body = { err: 1, msg: err.toString(), data: null };
  817. }
  818. }
  819. // 审批相关
  820. /**
  821. * 添加审批人
  822. * @param ctx
  823. * @return {Promise<void>}
  824. */
  825. async addAudit(ctx) {
  826. try {
  827. const data = JSON.parse(ctx.request.body.data);
  828. const id = this.app._.toInteger(data.auditorId);
  829. if (isNaN(id) || id <= 0) {
  830. throw '参数错误';
  831. }
  832. // 检查权限等
  833. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  834. throw '您无权添加审核人';
  835. }
  836. if (ctx.change.status === audit.change.status.checking || ctx.change.status === audit.change.status.checked) {
  837. throw '当前不允许添加审核人';
  838. }
  839. const auditorList = await ctx.service.changeAudit.getAuditors(ctx.change.cid, ctx.change.times);
  840. // 检查审核人是否已存在
  841. const exist = this.app._.find(auditorList, { uid: id });
  842. if (exist) {
  843. throw '该审核人已存在,请勿重复添加';
  844. }
  845. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdzs });
  846. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs ? 1 : 0;
  847. const result = await ctx.service.changeAudit.addAuditor(ctx.change.cid, id, ctx.change.times, is_gdzs);
  848. if (!result) {
  849. throw '添加审核人失败';
  850. }
  851. const auditors = await ctx.service.changeAudit.getUserGroup(ctx.change.cid, ctx.change.times);
  852. ctx.body = { err: 0, msg: '', data: auditors };
  853. } catch (err) {
  854. this.log(err);
  855. ctx.body = { err: 1, msg: err.toString(), data: null };
  856. }
  857. }
  858. /**
  859. * 移除审批人
  860. * @param ctx
  861. * @return {Promise<void>}
  862. */
  863. async deleteAudit(ctx) {
  864. try {
  865. const data = JSON.parse(ctx.request.body.data);
  866. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  867. if (isNaN(id) || id <= 0) {
  868. throw '参数错误';
  869. }
  870. const result = await ctx.service.changeAudit.deleteAuditor(ctx.change.cid, id, ctx.change.times);
  871. if (!result) {
  872. throw '移除审核人失败';
  873. }
  874. const auditors = await ctx.service.changeAudit.getUserGroup(ctx.change.cid, ctx.change.times);
  875. ctx.body = { err: 0, msg: '', data: auditors };
  876. } catch (err) {
  877. ctx.body = { err: 1, msg: err.toString(), data: null };
  878. }
  879. }
  880. async changeSpGroup(ctx) {
  881. try {
  882. const data = JSON.parse(ctx.request.body.data);
  883. const result = await ctx.service.changeAudit.changeSpGroup(ctx.change, data.sp_group);
  884. if (!result) {
  885. throw '切换审批组失败';
  886. }
  887. const auditors = await ctx.service.changeAudit.getUserGroup(ctx.change.cid, ctx.change.times);
  888. ctx.body = { err: 0, msg: '', data: auditors };
  889. } catch (err) {
  890. ctx.body = { err: 1, msg: err.toString(), data: null };
  891. }
  892. }
  893. async _getLedgerColumn() {
  894. const tender = this.ctx.tender;
  895. const ledgerColumn = [
  896. 'id', 'tender_id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf',
  897. 'code', 'b_code', 'name', 'unit', 'unit_price', 'quantity', 'total_price',
  898. 'sgfh_qty', 'sgfh_expr', 'sgfh_tp', 'memo', 'features', 'drawing_code', 'node_type', 'ex_qty1', 'ex_tp1', 'ccid'];
  899. if (tender.info.display.ledger.deal) ledgerColumn.push('deal_qty', 'deal_tp');
  900. if (tender.info.display.ledger.dgnQty) ledgerColumn.push('dgn_qty1', 'dgn_qty2');
  901. if (tender.info.display.ledger.clQty) ledgerColumn.push('sjcl_qty', 'qtcl_qty', 'sjcl_expr', 'qtcl_expr', 'sjcl_tp', 'qtcl_tp');
  902. const posColumn = ['id', 'tid', 'lid', 'name', 'position', 'porder', 'sgfh_qty', 'sgfh_expr', 'add_stage_order', 'drawing_code', 'quantity', 'ex_qty1', 'ccid'];
  903. if (tender.info.display.ledger.clQty) posColumn.push('sjcl_qty', 'qtcl_qty', 'sjcl_expr', 'qtcl_expr');
  904. const extraFields = await spreadSetting.getExtraFields(this.ctx, tender.id);
  905. if (extraFields.length > 0) {
  906. ledgerColumn.push(...extraFields);
  907. posColumn.push(...extraFields);
  908. }
  909. return [ledgerColumn, posColumn];
  910. }
  911. async defaultBills(ctx) {
  912. try {
  913. const filterField = true;
  914. const [ledgerColumn, posColumn] = await this._getLedgerColumn();
  915. // 判断是否台账修订中,修订中则不获取changeLedger及changePos值
  916. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  917. const data = JSON.parse(ctx.request.body.data);
  918. const readySettle = await ctx.service.settle.getReadySettle(ctx.tender.id);
  919. if (data.from === 'revise') await ctx.service.change.checkSettleUpdate(ctx.tender.id, readySettle);
  920. const ledgerData = await ctx.service.ledger.getAllDataByCondition({ columns: ledgerColumn, where: { tender_id: ctx.tender.id } });
  921. ledgerColumn.push('formc');
  922. const changeLedgerData = lastRevise && lastRevise.status !== audit.revise.status.checked && data.from !== 'revise' ? [] : await ctx.service.changeLedger.getAllDataByCondition({ columns: ledgerColumn, where: { tender_id: ctx.tender.id} });
  923. const posData = await ctx.service.pos.getPosData({tid: ctx.tender.id}, posColumn);
  924. posColumn.push('formc');
  925. const changePosData = lastRevise && lastRevise.status !== audit.revise.status.checked && data.from !== 'revise' ? [] : await ctx.service.changePos.getPosData({ tid: ctx.tender.id }, posColumn);
  926. // const ledgerData = await ctx.service.ledger.getData(ctx.tender.id);
  927. // const changeLedgerData = lastRevise && lastRevise.status !== audit.revise.status.checked && data.from !== 'revise' ? [] : await ctx.service.changeLedger.getData(ctx.tender.id);
  928. // const posData = await ctx.service.pos.getPosData({ tid: ctx.tender.id });
  929. // const changePosData = lastRevise && lastRevise.status !== audit.revise.status.checked && data.from !== 'revise' ? [] : await ctx.service.changePos.getPosData({ tid: ctx.tender.id });
  930. const dealBills = await ctx.service.dealBills.getAllDataByCondition({ where: { tender_id: ctx.tender.id } });
  931. // const settleStatus = ctx.service.settle.settleStatus;
  932. const settleBills = readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  933. const stages = data.from === 'revise' ? await ctx.service.stage.getAllDataByCondition({
  934. where: { tid: ctx.tender.id },
  935. orders: [['order', 'desc']],
  936. }) : [];
  937. if (stages.length > 0) {
  938. const usedBills = [],
  939. usedPos = [];
  940. for (const s of stages) {
  941. if (s.status === audit.stage.status.checked) {
  942. const usedPreBills = await ctx.service.stageBillsFinal.getUsedBills(ctx.tender.id, s.order);
  943. usedBills.push(...usedPreBills);
  944. const usedPrePos = await ctx.service.stagePosFinal.getUsedPos(ctx.tender.id, s.order);
  945. usedPos.push(...usedPrePos);
  946. break;
  947. } else {
  948. const usedCurBills = await ctx.service.stageBills.getStageUsedBills(ctx.tender.id, s.id);
  949. usedBills.push(...usedCurBills);
  950. const usedCurPos = await ctx.service.stagePos.getStageUsedPos(ctx.tender.id, s.id);
  951. usedPos.push(...usedCurPos);
  952. }
  953. }
  954. for (const b of ledgerData) {
  955. b.used = usedBills.indexOf(b.id) >= 0;
  956. }
  957. for (const p of posData) {
  958. p.used = usedPos.indexOf(p.id) >= 0;
  959. }
  960. }
  961. ctx.helper.assignRelaData(ledgerData, [
  962. { data: settleBills, fields: ['settle_status'], prefix: '', relaId: 'lid' },
  963. ]);
  964. const settlePos = readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  965. this.ctx.helper.assignRelaData(posData, [
  966. { data: settlePos, fields: ['settle_status'], prefix: '', relaId: 'pid' },
  967. { data: settlePos, fields: ['settle_status'], prefix: '', relaId: 'pid' },
  968. ]);
  969. // 标记ledger,搜索需求
  970. if (changePosData.length > 0) {
  971. const cplIdList = ctx.helper._.uniq(ctx.helper._.map(changePosData, 'lid'));
  972. const cLIdList = ctx.helper._.map(changeLedgerData, 'id');
  973. const ledgerIdList = [];
  974. for (const cp of cplIdList) {
  975. if (ctx.helper._.indexOf(cLIdList, cp) === -1) {
  976. ledgerIdList.push(cp);
  977. }
  978. }
  979. if (ledgerIdList.length > 0) {
  980. for (const lid of ledgerIdList) {
  981. const data = ctx.helper._.find(ledgerData, { id: lid });
  982. if (data) data.cid = 1;
  983. }
  984. }
  985. }
  986. const bodyData = { bills: ctx.helper._.concat(ledgerData, changeLedgerData), pos: ctx.helper._.concat(posData, changePosData), dealBills };
  987. if (data.from === 'batch') {
  988. bodyData.changeLedgerList = changeLedgerData;
  989. bodyData.changePosList = changePosData;
  990. }
  991. // hpack压缩数据
  992. const hpack = true;
  993. if (hpack) {
  994. bodyData.bills = this.ctx.helper.hpackArr(bodyData.bills);
  995. bodyData.pos = this.ctx.helper.hpackArr(bodyData.pos);
  996. ctx.body = { err: 0, msg: '', data: bodyData, hpack: ['bills', 'pos'] };
  997. } else {
  998. ctx.body = { err: 0, msg: '', data: bodyData };
  999. }
  1000. } catch (err) {
  1001. console.log(err);
  1002. this.log(err);
  1003. ctx.body = { err: 1, msg: err.toString(), data: [] };
  1004. }
  1005. }
  1006. /**
  1007. * 变更令上报和保存
  1008. * @param {Object} ctx - egg全局变量
  1009. * @return {void}
  1010. */
  1011. async save(ctx) {
  1012. // 变更令信息
  1013. const changeInfo = await ctx.service.change.getDataByCondition({ cid: ctx.request.body.cid });
  1014. try {
  1015. const result = await ctx.service.change.save(ctx.request.body, changeInfo.tid);
  1016. if (!result) {
  1017. throw '上报失败';
  1018. }
  1019. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  1020. ctx.body = { err: 0, msg: '保存成功' };
  1021. } else {
  1022. ctx.redirect('/tender/' + changeInfo.tid + '/change');
  1023. }
  1024. } catch (err) {
  1025. this.log(err);
  1026. if (ctx.request.body.changestatus !== undefined && parseInt(ctx.request.body.changestatus) === 2) {
  1027. ctx.body = { err: 1, msg: err.toString() };
  1028. } else {
  1029. ctx.redirect('/tender/' + changeInfo.tid + '/change/' + ctx.request.body.cid + '/info');
  1030. }
  1031. }
  1032. }
  1033. /**
  1034. * 变更令审批
  1035. * @param {Object} ctx - egg全局变量
  1036. * @return {void}
  1037. */
  1038. async approval(ctx) {
  1039. const data = JSON.parse(ctx.request.body.data);
  1040. const responseData = {
  1041. err: 0,
  1042. msg: '',
  1043. data: {},
  1044. };
  1045. try {
  1046. const changeData = await ctx.service.change.getDataByCondition({ cid: data.change_id });
  1047. if (!changeData) {
  1048. throw '变更令数据错误';
  1049. }
  1050. const status = parseInt(data.status);
  1051. // 判断是否到你审批,如果不是则无法审批
  1052. const curAuditor = await ctx.service.changeAudit.getCurAuditors(changeData.cid, changeData.times);
  1053. if (!curAuditor || (curAuditor && ctx.helper._.findIndex(curAuditor, { uid: ctx.session.sessionUser.accountId }) === -1)) {
  1054. throw '该变更令当前您无权操作';
  1055. }
  1056. const readySettle = await ctx.service.settle.getReadySettle(changeData.tid);
  1057. if (readySettle && readySettle.settle_order !== ctx.tender.data.settle_order) {
  1058. throw '结算数据发生变化,请刷新页面再提交';
  1059. }
  1060. let result = false;
  1061. const pid = this.ctx.session.sessionProject.id;
  1062. switch (status) {
  1063. case 3:// 审批通过
  1064. result = await ctx.service.change.approvalSuccess(pid, data, changeData);
  1065. break;
  1066. // case 4:// 审批终止
  1067. // result = await ctx.service.change.approvalStop(ctx.request.body);
  1068. // break;
  1069. case 5:// 审批退回到原报人
  1070. result = await ctx.service.change.approvalCheckNo(pid, data, changeData);
  1071. break;
  1072. case 6:// 审批退回到上一个审批人
  1073. result = await ctx.service.change.approvalCheckNoPre(pid, data, changeData);
  1074. break;
  1075. default:break;
  1076. }
  1077. if (!result) {
  1078. throw '审批失败';
  1079. }
  1080. ctx.body = responseData;
  1081. } catch (err) {
  1082. console.log(err);
  1083. // ctx.session.postError = err.toString();
  1084. // ctx.redirect(ctx.request.header.referer);
  1085. ctx.body = { err: 1, msg: err.toString(), data: null };
  1086. }
  1087. }
  1088. /**
  1089. * 撤回审批
  1090. * @param ctx
  1091. * @return {Promise<void>}
  1092. */
  1093. async checkAuditCancel(ctx) {
  1094. try {
  1095. if (!ctx.change.cancancel) throw '您无权进行该操作';
  1096. if (ctx.change.readySettle && ctx.change.readySettle.settle_order !== ctx.tender.data.settle_order) {
  1097. throw '结算数据发生变化,请刷新页面再提交';
  1098. }
  1099. await ctx.service.changeAudit.checkCancel(ctx.change);
  1100. ctx.body = { err: 0, url: ctx.request.header.referer, msg: '' };
  1101. } catch (err) {
  1102. this.log(err);
  1103. ctx.body = { err: 1, msg: err };
  1104. }
  1105. }
  1106. /**
  1107. * 变更公司管理
  1108. * @param {Object} ctx - egg全局变量
  1109. * @return {void}
  1110. */
  1111. async updateCompany(ctx) {
  1112. const responseData = {
  1113. err: 0,
  1114. msg: '',
  1115. data: '',
  1116. };
  1117. try {
  1118. const data = JSON.parse(ctx.request.body.data);
  1119. if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1120. throw '参数有误';
  1121. }
  1122. const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1123. responseData.data = { add: addCompany, select: selectCompany };
  1124. } catch (err) {
  1125. responseData.err = 1;
  1126. responseData.msg = err;
  1127. }
  1128. ctx.body = responseData;
  1129. }
  1130. /**
  1131. * 上传附件
  1132. * @param {Object} ctx - egg全局变量
  1133. * @return {void}
  1134. */
  1135. async uploadFile(ctx) {
  1136. const responseData = {
  1137. err: 0,
  1138. msg: '',
  1139. data: [],
  1140. };
  1141. let stream;
  1142. try {
  1143. const parts = ctx.multipart({ autoFields: true });
  1144. const files = [];
  1145. let index = 0;
  1146. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1147. const extra_upload = change.status === audit.change.status.checked;
  1148. while ((stream = await parts()) !== undefined) {
  1149. // 判断用户是否选择上传文件
  1150. if (!stream.filename) {
  1151. throw '请选择上传的文件!';
  1152. }
  1153. // const create_time = Date.parse(new Date()) / 1000;
  1154. // const fileInfo = path.parse(stream.filename);
  1155. // const dirName = 'app/public/upload/changes/' + moment().format('YYYYMMDD');
  1156. // const fileName = 'changes' + create_time + '_' + index + fileInfo.ext;
  1157. // // 判断文件夹是否存在,不存在则直接创建文件夹
  1158. // if (!fs.existsSync(path.join(this.app.baseDir, dirName))) {
  1159. // await fs.mkdirSync(path.join(this.app.baseDir, dirName));
  1160. // }
  1161. // // 保存文件
  1162. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, dirName, fileName));
  1163. const fileInfo = path.parse(stream.filename);
  1164. const create_time = Date.parse(new Date()) / 1000;
  1165. // const filepath = `app/public/upload/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  1166. const filepath = `app/public/upload/${parts.field.tid}/change/fujian_${create_time + index.toString() + fileInfo.ext}`;
  1167. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, filepath));
  1168. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  1169. await sendToWormhole(stream);
  1170. // 保存数据到att表
  1171. const fileData = {
  1172. in_time: create_time,
  1173. filename: fileInfo.name,
  1174. fileext: fileInfo.ext,
  1175. filesize: Array.isArray(parts.field.size) ? parts.field.size[index] : parts.field.size,
  1176. filepath,
  1177. extra_upload,
  1178. };
  1179. const result = await ctx.service.changeAtt.save(parts.field, fileData, ctx.session.sessionUser.accountId);
  1180. if (!result) {
  1181. throw '导入数据库保存失败';
  1182. }
  1183. // fileData.in_time = moment(create_time * 1000).format('YYYY-MM-DD');
  1184. // fileData.filesize = await ctx.helper.bytesToSize(fileData.filesize);
  1185. fileData.uid = ctx.session.sessionUser.accountId;
  1186. fileData.id = result.insertId;
  1187. fileData.orginpath = ctx.app.config.fujianOssPath + filepath;
  1188. delete fileData.filepath;
  1189. if (!ctx.helper.canPreview(fileData.fileext)) {
  1190. fileData.filepath = `/change/download/file/${fileData.id}`;
  1191. } else {
  1192. fileData.filepath = ctx.app.config.fujianOssPath + filepath;
  1193. }
  1194. files.push(fileData);
  1195. ++index;
  1196. }
  1197. responseData.data = files;
  1198. } catch (err) {
  1199. this.log(err);
  1200. // 失败需要消耗掉stream 以防卡死
  1201. if (stream) {
  1202. await sendToWormhole(stream);
  1203. }
  1204. this.setMessage(err.toString(), this.messageType.ERROR);
  1205. }
  1206. ctx.body = responseData;
  1207. }
  1208. /**
  1209. * 下载附件
  1210. * @param {Object} ctx - egg全局变量
  1211. * @return {void}
  1212. */
  1213. async downloadFile(ctx) {
  1214. const id = ctx.params.id;
  1215. if (id) {
  1216. try {
  1217. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1218. if (fileInfo !== undefined && fileInfo !== '') {
  1219. // const fileName = path.join(this.app.baseDir, fileInfo.filepath);
  1220. // 解决中文无法下载问题
  1221. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1222. let disposition = '';
  1223. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1224. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename + fileInfo.fileext);
  1225. } else if (userAgent.indexOf('firefox') >= 0) {
  1226. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename + fileInfo.fileext) + '"';
  1227. } else {
  1228. /* safari等其他非主流浏览器只能自求多福了 */
  1229. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename + fileInfo.fileext).toString('binary');
  1230. }
  1231. ctx.response.set({
  1232. 'Content-Type': 'application/octet-stream',
  1233. 'Content-Disposition': disposition,
  1234. 'Content-Length': fileInfo.filesize,
  1235. });
  1236. // ctx.body = await fs.createReadStream(fileName);
  1237. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  1238. } else {
  1239. throw '不存在该文件';
  1240. }
  1241. } catch (err) {
  1242. this.log(err);
  1243. this.setMessage(err.toString(), this.messageType.ERROR);
  1244. }
  1245. }
  1246. }
  1247. /**
  1248. * 批量下载 - 压缩成zip文件返回
  1249. * @param {Oject} ctx - 全局上下文
  1250. */
  1251. async downloadZip(ctx) {
  1252. const time = Date.now();
  1253. const zipPath = `app/public/upload/change/fu_jian_zip${time}.zip`;
  1254. const responseData = {
  1255. err: 0,
  1256. msg: '',
  1257. };
  1258. try {
  1259. // const fileIds = JSON.parse(ctx.request.query.fileIds);
  1260. const { fileIds = [] } = JSON.parse(ctx.request.body.data);
  1261. const { name: changeName } = await ctx.service.changeAtt.getChangeName(ctx.params.cid);
  1262. const zipFilename = `${ctx.tender.data.name}-工程变更-${changeName}-附件.zip`;
  1263. const size = await ctx.service.changeAtt.compressedFile(fileIds, zipPath);
  1264. // 解决中文无法下载问题
  1265. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  1266. let disposition = '';
  1267. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  1268. disposition = 'attachment; filename=' + encodeURIComponent(zipFilename);
  1269. } else if (userAgent.indexOf('firefox') >= 0) {
  1270. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(zipFilename) + '"';
  1271. } else {
  1272. /* safari等其他非主流浏览器只能自求多福了 */
  1273. disposition = 'attachment; filename=' + new Buffer(zipFilename).toString('binary');
  1274. }
  1275. ctx.response.set({
  1276. 'Content-Type': 'application/octet-stream',
  1277. 'Content-Disposition': disposition,
  1278. 'Content-Length': size,
  1279. });
  1280. const readStream = fs.createReadStream(path.join(this.app.baseDir, zipPath));
  1281. ctx.body = readStream;
  1282. // ctx.body = fs.readFileSync(path.resolve(this.app.baseDir, zipPath));
  1283. readStream.on('close', () => {
  1284. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1285. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1286. }
  1287. });
  1288. // fs的错误不能被try catch捕捉
  1289. readStream.on('error', err => {
  1290. this.log(err);
  1291. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1292. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1293. }
  1294. responseData.err = 1;
  1295. responseData.msg = err.toString();
  1296. ctx.body = responseData;
  1297. });
  1298. } catch (err) {
  1299. this.log(err);
  1300. if (fs.existsSync(path.resolve(this.app.baseDir, zipPath))) {
  1301. fs.unlinkSync(path.resolve(this.app.baseDir, zipPath));
  1302. }
  1303. this.setMessage(err.toString(), this.messageType.ERROR);
  1304. responseData.err = 1;
  1305. responseData.msg = err.toString();
  1306. ctx.body = responseData;
  1307. }
  1308. }
  1309. /**
  1310. * 删除附件
  1311. * @param {Object} ctx - egg全局变量
  1312. * @return {void}
  1313. */
  1314. async deleteFile(ctx) {
  1315. const responseData = {
  1316. err: 0,
  1317. msg: '',
  1318. data: '',
  1319. };
  1320. try {
  1321. const data = JSON.parse(ctx.request.body.data);
  1322. const change = await ctx.service.change.getDataByCondition({ cid: ctx.params.cid });
  1323. const fileInfo = await ctx.service.changeAtt.getDataById(data.id);
  1324. if (!fileInfo || !Object.keys(fileInfo).length) {
  1325. throw '该文件不存在';
  1326. }
  1327. const accountInfo = await this.ctx.service.projectAccount.getDataById(this.ctx.session.sessionUser.accountId);
  1328. const userPermission = accountInfo && accountInfo.permission ? JSON.parse(accountInfo.permission) : null;
  1329. const deleteFilePermission = !!(userPermission && userPermission.change !== undefined && userPermission.change.indexOf('2') !== -1);
  1330. if (!fileInfo.extra_upload && change.status === audit.change.status.checked && !deleteFilePermission) {
  1331. throw '无权限删除';
  1332. }
  1333. if (fileInfo !== undefined && fileInfo !== '') {
  1334. // 先删除文件
  1335. // await fs.unlinkSync(path.join(this.app.baseDir, fileInfo.filepath));
  1336. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  1337. // 再删除数据库
  1338. await ctx.service.changeAtt.deleteById(data.id);
  1339. responseData.data = '';
  1340. } else {
  1341. throw '不存在该文件';
  1342. }
  1343. // if (data.tid === undefined || data.uci === undefined || data.uc === undefined || data.ac === undefined) {
  1344. // throw '参数有误';
  1345. // }
  1346. // const [addCompany, selectCompany] = await ctx.service.changeCompany.setCompanyList(data);
  1347. // responseData.data = { add: addCompany, select: selectCompany };
  1348. } catch (err) {
  1349. responseData.err = 1;
  1350. responseData.msg = err;
  1351. }
  1352. ctx.body = responseData;
  1353. }
  1354. /**
  1355. * 查看附件
  1356. * @param {Object} ctx - egg全局变量
  1357. * @return {void}
  1358. */
  1359. async checkFile(ctx) {
  1360. const responseData = { err: 0, msg: '' };
  1361. const id = parseInt(ctx.params.id);
  1362. if (id) {
  1363. try {
  1364. const fileInfo = await ctx.service.changeAtt.getDataById(id);
  1365. if (fileInfo && Object.keys(fileInfo).length) {
  1366. let filepath = fileInfo.filepath;
  1367. if (!ctx.helper.canPreview(fileInfo.fileext)) {
  1368. filepath = `/change/download/file/${fileInfo.id}`;
  1369. } else {
  1370. filepath = filepath.replace(/^app|\/app/, '');
  1371. }
  1372. fileInfo.filepath && (responseData.data = { filepath });
  1373. }
  1374. } catch (error) {
  1375. this.log(error);
  1376. this.setMessage(error.toString(), this.messageType.ERROR);
  1377. responseData.err = 1;
  1378. responseData.msg = error.toString();
  1379. }
  1380. }
  1381. ctx.body = responseData;
  1382. }
  1383. /**
  1384. * 删除变更令
  1385. * @param {Object} ctx - egg全局变量
  1386. * @return {void}
  1387. */
  1388. async delete(ctx) {
  1389. try {
  1390. const result = await ctx.service.change.delete(ctx.request.body.cid);
  1391. if (!result) {
  1392. throw '删除变更令失败';
  1393. }
  1394. ctx.redirect(ctx.request.header.referer);
  1395. } catch (err) {
  1396. console.log(err);
  1397. ctx.redirect(ctx.request.header.referer);
  1398. }
  1399. }
  1400. /**
  1401. * 变更令重新审批
  1402. * @param {Object} ctx - egg全局变量
  1403. * @return {void}
  1404. */
  1405. async checkAgain(ctx) {
  1406. try {
  1407. const readySettle = await ctx.service.settle.getReadySettle(ctx.change.tid);
  1408. if (readySettle && readySettle.settle_order !== ctx.tender.data.settle_order) {
  1409. throw '结算数据发生变化,请刷新页面再提交';
  1410. }
  1411. if (ctx.session.sessionUser.loginStatus === 0) {
  1412. const code = ctx.request.body.code;
  1413. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1414. if (!pa.auth_mobile) {
  1415. throw '未绑定手机号';
  1416. }
  1417. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1418. const cacheCode = await app.redis.get(cacheKey);
  1419. // console.log(cacheCode);
  1420. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1421. throw '验证码不正确!';
  1422. }
  1423. }
  1424. // 重新审批
  1425. if ((ctx.change.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0) && ctx.change.status === audit.change.status.checked) {
  1426. const result = await ctx.service.change.checkAgain(ctx.change);
  1427. if (!result) {
  1428. throw '重新审批失败';
  1429. }
  1430. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1431. ctx.body = {
  1432. err: 0,
  1433. url: ctx.request.header.referer,
  1434. msg: '',
  1435. };
  1436. } else {
  1437. throw '您无权进行该操作';
  1438. }
  1439. } catch (err) {
  1440. console.log(err);
  1441. // ctx.redirect(ctx.request.header.referer);
  1442. ctx.body = {
  1443. err: 1,
  1444. // url: ctx.request.header.referer,
  1445. msg: err,
  1446. };
  1447. }
  1448. }
  1449. /**
  1450. * 变更令修订重新上报
  1451. * @param {Object} ctx - egg全局变量
  1452. * @return {void}
  1453. */
  1454. async checkRevise(ctx) {
  1455. try {
  1456. if (ctx.change.status !== audit.change.status.checked || ctx.session.sessionUser.accountId !== ctx.change.uid) {
  1457. throw '您无权进行该操作';
  1458. }
  1459. const readySettle = await ctx.service.settle.getReadySettle(ctx.change.tid);
  1460. if (readySettle && readySettle.settle_order !== ctx.tender.data.settle_order) {
  1461. throw '结算数据发生变化,请刷新页面再提交';
  1462. }
  1463. if (ctx.session.sessionUser.loginStatus === 0) {
  1464. const code = ctx.request.body.code;
  1465. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  1466. if (!pa.auth_mobile) {
  1467. throw '未绑定手机号';
  1468. }
  1469. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  1470. const cacheCode = await app.redis.get(cacheKey);
  1471. // console.log(cacheCode);
  1472. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  1473. throw '验证码不正确!';
  1474. }
  1475. }
  1476. // 获取是否已存在调用变更令
  1477. // const changeUsedData = await ctx.service.stageChange.getAllFinalUsedData(ctx.tender.id, changeData.cid);
  1478. // const stageChangeNum = this.ctx.helper.sum(changeUsedData.map(x => { return Math.abs(x.qty); }));
  1479. // if (stageChangeNum !== 0) {
  1480. // throw '该变更令已被调用,无法重新审批';
  1481. // }
  1482. // 重新审批
  1483. const result = await ctx.service.change.checkRevise(ctx.change);
  1484. if (!result) {
  1485. throw '修订发起失败';
  1486. }
  1487. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  1488. ctx.body = {
  1489. err: 0,
  1490. url: ctx.request.header.referer,
  1491. msg: '',
  1492. };
  1493. } catch (err) {
  1494. console.log(err);
  1495. // ctx.redirect(ctx.request.header.referer);
  1496. ctx.body = {
  1497. err: 1,
  1498. // url: ctx.request.header.referer,
  1499. msg: err,
  1500. };
  1501. }
  1502. }
  1503. /**
  1504. * 变更令撤销修订
  1505. * @param {Object} ctx - egg全局变量
  1506. * @return {void}
  1507. */
  1508. async cancelRevise(ctx) {
  1509. try {
  1510. if (!(ctx.change.status === audit.change.status.revise && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.session.sessionUser.accountId === ctx.session.sessionUser.is_admin))) {
  1511. throw '您无权进行该操作';
  1512. }
  1513. const readySettle = await ctx.service.settle.getReadySettle(ctx.change.tid);
  1514. if (readySettle && readySettle.settle_order !== ctx.tender.data.settle_order) {
  1515. throw '结算数据发生变化,请刷新页面再提交';
  1516. }
  1517. // 重新审批
  1518. const result = await ctx.service.change.cancelRevise(ctx.change.cid, ctx.change.times);
  1519. if (!result) {
  1520. throw '撤销修订失败';
  1521. }
  1522. ctx.body = {
  1523. err: 0,
  1524. url: ctx.request.header.referer,
  1525. msg: '',
  1526. };
  1527. } catch (err) {
  1528. console.log(err);
  1529. ctx.body = {
  1530. err: 1,
  1531. msg: err,
  1532. };
  1533. }
  1534. }
  1535. async saveAudit(ctx) {
  1536. try {
  1537. // if (ctx.change.revising) {
  1538. // throw '台账修订中,请勿修改提交期数据';
  1539. // }
  1540. const data = JSON.parse(ctx.request.body.data);
  1541. if (ctx.session.sessionUser.is_admin && ctx.change.status !== audit.change.status.checked) {
  1542. await ctx.service.changeAudit.saveAudit(ctx.change.cid, ctx.change.times, ctx.change.sp_group, data);
  1543. const auditors = await ctx.service.changeAudit.getUniqUserGroup(ctx.change.cid, ctx.change.times);
  1544. ctx.body = { err: 0, msg: '', data: auditors };
  1545. } else {
  1546. throw '您无权进行该操作';
  1547. }
  1548. } catch (err) {
  1549. this.log(err);
  1550. // ctx.session.postError = err.toString();
  1551. // ctx.redirect(ctx.request.header.referer);
  1552. ctx.body = {
  1553. err: 1,
  1554. // url: ctx.request.header.referer,
  1555. msg: err,
  1556. };
  1557. }
  1558. }
  1559. /**
  1560. * 获取变更清单
  1561. * @param ctx
  1562. * @return {Promise<void>}
  1563. */
  1564. async bills(ctx) {
  1565. try {
  1566. const data = JSON.parse(ctx.request.body.data);
  1567. const responseData = { err: 0, msg: '', data: [] };
  1568. switch (data.type) {
  1569. case 'gather':
  1570. responseData.data = await ctx.service.changeAuditList.gatherBgBills(ctx.tender.id);
  1571. responseData.data.sort((a, b) => { return ctx.helper.compareCode(a.code, b.code); });
  1572. break;
  1573. default:
  1574. throw '查询的数据不存在';
  1575. }
  1576. ctx.body = responseData;
  1577. } catch (err) {
  1578. this.log(err);
  1579. this.ajaxErrorBody(err, '获取变更清单失败');
  1580. }
  1581. }
  1582. /**
  1583. * 最后审批人审批成功检查批复编号和其它变更令是否出现重名情况
  1584. * @param ctx
  1585. * @return {Promise<void>}
  1586. */
  1587. async checkCodeRepeat(ctx) {
  1588. const responseData = {
  1589. err: 0,
  1590. msg: '',
  1591. data: '',
  1592. };
  1593. try {
  1594. const tenderId = ctx.params.id;
  1595. const cid = ctx.params.cid;
  1596. const data = JSON.parse(ctx.request.body.data);
  1597. const result = await ctx.service.change.isRepeat(cid, data.p_code, tenderId);
  1598. if (result) {
  1599. throw '该变更令号(批复编号)已使用';
  1600. }
  1601. } catch (err) {
  1602. responseData.err = 1;
  1603. responseData.msg = err;
  1604. }
  1605. ctx.body = responseData;
  1606. }
  1607. /**
  1608. * 拷贝其他变更令
  1609. * @param {object} ctx - 全局上下文
  1610. */
  1611. async copyChange(ctx) {
  1612. const responseData = {
  1613. err: 0,
  1614. msg: '',
  1615. data: '',
  1616. };
  1617. try {
  1618. const cid = ctx.params.cid;
  1619. const copy_cid = JSON.parse(ctx.request.body.data);
  1620. const result = await ctx.service.change.handleCopyChange(cid, copy_cid);
  1621. if (!result) {
  1622. responseData.err = 1;
  1623. responseData.msg = '拷贝失败!';
  1624. }
  1625. } catch (error) {
  1626. responseData.err = 1;
  1627. responseData.msg = error;
  1628. }
  1629. ctx.body = responseData;
  1630. }
  1631. /**
  1632. * 修订 详细页面(添加台账清单-台账模式)(Get)
  1633. * @param ctx
  1634. * @return {Promise<void>}
  1635. */
  1636. async reviseInfo(ctx) {
  1637. try {
  1638. // if (!ctx.session.sessionProject.page_show.openChangeRevise) {
  1639. // throw '该功能已关闭';
  1640. // }
  1641. const change = ctx.change;
  1642. let edit = true;
  1643. let changing = false;
  1644. if (change.status !== audit.change.status.uncheck && change.status !== audit.change.status.checkNo && change.status !== audit.change.status.revise) {
  1645. // throw '本条变更审批中或已完成,无法操作台账数据';
  1646. edit = false;
  1647. changing = true;
  1648. }
  1649. let revising = false;
  1650. // 判断是否在修订中,是则无法操作本页
  1651. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  1652. if (lastRevise && lastRevise.status !== audit.revise.status.checked) {
  1653. // throw '台账修订中,无法操作台账数据';
  1654. edit = false;
  1655. revising = true;
  1656. }
  1657. change.order_site_msg = change.order_site ? await ctx.service.changeAuditList.getDataById(change.order_site) : null;
  1658. const renderData = await this._getDefaultReviseInfoData(ctx, change, !edit);
  1659. // 获取原报dsk数据
  1660. const accountInfo = await ctx.service.projectAccount.getDataById(change.uid);
  1661. renderData.changeList = await ctx.service.changeAuditList.getList(change.cid);
  1662. let changeUsedData = await ctx.service.stageChange.getAllFinalUsedData(ctx.tender.id, change.cid);
  1663. changeUsedData = ctx.helper._.orderBy(ctx.helper._.filter(changeUsedData, function(item) {
  1664. return item.qty !== null;
  1665. }), ['sorder'], ['desc']);
  1666. const useChangeUsedData = [];
  1667. if (changeUsedData.length > 0) { // 防止未创建期时调用
  1668. for (const cu of changeUsedData) {
  1669. const index = ctx.helper._.findIndex(useChangeUsedData, { cbid: cu.cbid });
  1670. if (index !== -1) {
  1671. useChangeUsedData[index].qty = ctx.helper.add(useChangeUsedData[index].qty, cu.qty);
  1672. } else {
  1673. useChangeUsedData.push(cu);
  1674. }
  1675. }
  1676. }
  1677. renderData.changeUsedData = useChangeUsedData;
  1678. const readySettle = await ctx.service.settle.getReadySettle(ctx.tender.id);
  1679. renderData.settleBills = readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  1680. renderData.settlePos = readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  1681. renderData.dskAccountData = accountInfo && accountInfo.dsk_account ? JSON.parse(accountInfo.dsk_account) : {};
  1682. renderData.dskProjects = accountInfo && accountInfo.dsk_account && accountInfo.dsk_projects ? JSON.parse(accountInfo.dsk_projects) : [];
  1683. // 台账只读、使用数据
  1684. renderData.readOnly = !edit;
  1685. renderData.changing = changing;
  1686. renderData.revising = revising;
  1687. renderData.isYb = change.uid === ctx.session.sessionUser.accountId;
  1688. await this.layout('change/revise.ejs', renderData, 'change/revise_modal.ejs');
  1689. } catch (err) {
  1690. this.log(err);
  1691. ctx.redirect(ctx.request.header.referer);
  1692. }
  1693. }
  1694. /**
  1695. * 修订 详细页面(添加台账清单-清单模式)(Get)
  1696. * @param ctx
  1697. * @return {Promise<void>}
  1698. */
  1699. async addListInfo(ctx) {
  1700. try {
  1701. const change = ctx.change;
  1702. let edit = true;
  1703. let changing = false;
  1704. if (change.status !== audit.change.status.uncheck && change.status !== audit.change.status.checkNo && change.status !== audit.change.status.revise) {
  1705. // throw '本条变更审批中或已完成,无法操作台账数据';
  1706. edit = false;
  1707. changing = true;
  1708. }
  1709. change.order_site_msg = change.order_site ? await ctx.service.changeAuditList.getDataById(change.order_site) : null;
  1710. const renderData = {
  1711. change,
  1712. tpUnit: change.tp_decimal ? change.tp_decimal : ctx.tender.info.decimal.tp,
  1713. upUnit: change.up_decimal ? change.up_decimal : ctx.tender.info.decimal.up,
  1714. precision: ctx.tender.info.precision,
  1715. tender: ctx.tender.data,
  1716. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  1717. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.addList),
  1718. auditConst: audit.change,
  1719. settleStatus: ctx.service.settle.settleStatus,
  1720. };
  1721. // 获取原报dsk数据
  1722. const accountInfo = await ctx.service.projectAccount.getDataById(change.uid);
  1723. renderData.changeList = await ctx.service.changeAuditList.getList(change.cid);
  1724. let changeUsedData = await ctx.service.stageChange.getAllFinalUsedData(ctx.tender.id, change.cid);
  1725. changeUsedData = ctx.helper._.orderBy(ctx.helper._.filter(changeUsedData, function(item) {
  1726. return item.qty !== null;
  1727. }), ['sorder'], ['desc']);
  1728. const useChangeUsedData = [];
  1729. if (changeUsedData.length > 0) { // 防止未创建期时调用
  1730. for (const cu of changeUsedData) {
  1731. const index = ctx.helper._.findIndex(useChangeUsedData, { cbid: cu.cbid });
  1732. if (index !== -1) {
  1733. useChangeUsedData[index].qty = ctx.helper.add(useChangeUsedData[index].qty, cu.qty);
  1734. } else {
  1735. useChangeUsedData.push(cu);
  1736. }
  1737. }
  1738. }
  1739. renderData.changeUsedData = useChangeUsedData;
  1740. const readySettle = await ctx.service.settle.getReadySettle(ctx.tender.id);
  1741. renderData.settleBills = readySettle ? await this.ctx.service.settleBills.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  1742. renderData.settlePos = readySettle ? await this.ctx.service.settlePos.getAllDataByCondition({ where: { settle_id: readySettle.id } }) : [];
  1743. // 台账只读、使用数据
  1744. renderData.readOnly = !edit;
  1745. renderData.changing = changing;
  1746. renderData.isYb = change.uid === ctx.session.sessionUser.accountId;
  1747. await this.layout('change/addlist.ejs', renderData, 'change/addlist_modal.ejs');
  1748. } catch (err) {
  1749. this.log(err);
  1750. ctx.redirect(ctx.request.header.referer);
  1751. }
  1752. }
  1753. async _getDefaultReviseInfoData(ctx, change, edit) {
  1754. const [ledgerSpread, posSpread] = await spreadSetting.getLedgerSpreadSetting(ctx, change.tid, edit);
  1755. const [stdBills, stdChapters] = await this.ctx.service.valuation.getValuationStdList(
  1756. ctx.tender.data.valuation, ctx.tender.data.measure_type);
  1757. return {
  1758. change,
  1759. tender: ctx.tender.data,
  1760. ledgerSpread, posSpread, tenderMenu, measureType,
  1761. preUrl: '/tender/' + ctx.tender.id + '/change/' + ctx.change.cid + '/information',
  1762. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.revise),
  1763. stdBills,
  1764. auditConst: audit.flow,
  1765. audit: audit.flow,
  1766. stdChapters,
  1767. nodeType: stdConst.nodeType,
  1768. settleStatus: ctx.service.settle.settleStatus,
  1769. precision: ctx.tender.info.precision,
  1770. };
  1771. }
  1772. async updateRevise(ctx) {
  1773. try {
  1774. if (!ctx.tender.data) throw '标段数据错误';
  1775. const data = JSON.parse(ctx.request.body.data);
  1776. if (!data.postType || !data.postData) throw '数据错误';
  1777. const responseData = { err: 0, msg: '', data: {} };
  1778. const change = ctx.change;
  1779. if (change.status !== audit.change.status.uncheck && change.status !== audit.change.status.checkNo && change.status !== audit.change.status.revise) {
  1780. throw '该变更令正在审批中或已完成,无法操作新增部位数据';
  1781. }
  1782. // 判断是否在修订中,是则无法操作本页
  1783. const lastRevise = await ctx.service.ledgerRevise.getLastestRevise(ctx.tender.id);
  1784. if (lastRevise && lastRevise.status !== audit.revise.status.checked) {
  1785. throw '台账修订中,无法操作新增部位数据';
  1786. }
  1787. // const revise = await this.checkRevise(ctx);
  1788. //
  1789. switch (data.postType) {
  1790. case 'add':
  1791. case 'delete':
  1792. case 'up-move':
  1793. case 'down-move':
  1794. case 'up-level':
  1795. case 'down-level':
  1796. responseData.data = await this._billsBase(ctx, data.postType, data.postData);
  1797. break;
  1798. case 'update':
  1799. ctx.helper.checkDgnQtyPrecision(data.postData);
  1800. responseData.data = await ctx.service.changeLedger.updateCalc(ctx.tender.id, data.postData);
  1801. break;
  1802. case 'paste-block':
  1803. responseData.data = await this._pasteBlock(ctx, data.postData);
  1804. break;
  1805. case 'add-std':
  1806. responseData.data = await this._addStd(ctx, data.postData);
  1807. break;
  1808. case 'add-deal':
  1809. responseData.data = await this._addDeal(ctx, data.postData);
  1810. break;
  1811. // case 'batch-insert':
  1812. // responseData.data = await this._batchInsert(ctx, data.postData);
  1813. // break;
  1814. case 'pos':
  1815. responseData.data = await this._updatePos(ctx, data);
  1816. break;
  1817. default:
  1818. throw '未知操作';
  1819. }
  1820. responseData.data.changeList = await ctx.service.changeAuditList.getList(ctx.change.cid);
  1821. ctx.body = responseData;
  1822. } catch (err) {
  1823. console.log(err);
  1824. this.log(err);
  1825. ctx.body = this.ajaxErrorBody(err, '数据错误');
  1826. }
  1827. }
  1828. async _billsBase(ctx, type, data) {
  1829. if (isNaN(data.id) || data.id <= 0) throw '数据错误';
  1830. if (type !== 'add') {
  1831. if (isNaN(data.count) || data.count <= 0) data.count = 1;
  1832. }
  1833. switch (type) {
  1834. case 'add':
  1835. return await ctx.service.changeLedger.addNodeBatch(ctx.tender.id, data.id, { ccid: ctx.change.cid, check_calc: 1 }, data.count);
  1836. case 'delete':
  1837. return await ctx.service.changeLedger.delete(ctx.tender.id, data.id, data.count);
  1838. case 'up-move':
  1839. return await ctx.service.changeLedger.upMoveNode(ctx.tender.id, data.id, data.count);
  1840. case 'down-move':
  1841. return await ctx.service.changeLedger.downMoveNode(ctx.tender.id, data.id, data.count);
  1842. case 'up-level':
  1843. return await ctx.service.changeLedger.upLevelNode(ctx.tender.id, data.id, data.count);
  1844. case 'down-level':
  1845. return await ctx.service.changeLedger.downLevelNode(ctx.tender.id, data.id, data.count);
  1846. default:
  1847. throw '未知操作';
  1848. }
  1849. }
  1850. /**
  1851. * 复制粘贴整块
  1852. *
  1853. * @param ctx
  1854. * @return {Promise<void>}
  1855. */
  1856. async _pasteBlock(ctx, data) {
  1857. if ((isNaN(data.id) || data.id <= 0) ||
  1858. (!data.tid && data.tid <= 0) ||
  1859. (!data.block || data.block.length <= 0)) throw '参数错误';
  1860. return await ctx.service.changeLedger.pasteBlockData(ctx.tender.id, data.id, data.block);
  1861. }
  1862. /**
  1863. * 从标准项目表添加数据
  1864. * @param ctx
  1865. * @return {Promise<void>}
  1866. */
  1867. async _addStd(ctx, data) {
  1868. if ((isNaN(data.id) || data.id <= 0) || !data.stdType || !data.stdNode) throw '参数错误';
  1869. // todo 校验项目是否使用该库的权限
  1870. let stdLib,
  1871. addType;
  1872. switch (data.stdType) {
  1873. case 'xmj':
  1874. stdLib = ctx.service.stdXmj;
  1875. addType = stdDataAddType.withParent;
  1876. break;
  1877. case 'gcl':
  1878. stdLib = ctx.service.stdGcl;
  1879. const selectNode = await ctx.service.changeLedger.getDataByNodeId(ctx.tender.id, data.id) || await ctx.service.ledger.getDataByNodeId(ctx.tender.id, data.id);
  1880. if (selectNode.b_code) {
  1881. addType = stdDataAddType.next;
  1882. } else {
  1883. addType = stdDataAddType.child;
  1884. }
  1885. break;
  1886. default:
  1887. throw '未知标准库';
  1888. }
  1889. const stdData = await stdLib.getDataByDataId(data.stdLibId, data.stdNode);
  1890. switch (addType) {
  1891. case stdDataAddType.child:
  1892. return await ctx.service.changeLedger.addStdNodeAsChild(ctx.tender.id, data.id, stdData, ctx.change.cid);
  1893. case stdDataAddType.next:
  1894. return await ctx.service.changeLedger.addStdNode(ctx.tender.id, data.id, stdData, ctx.change.cid);
  1895. case stdDataAddType.withParent:
  1896. return await ctx.service.changeLedger.addStdNodeWithParent(ctx.tender.id, stdData, stdLib, ctx.change.cid);
  1897. default:
  1898. throw '未知添加方式';
  1899. }
  1900. }
  1901. /**
  1902. * 从签约清单添加节点
  1903. * @param ctx
  1904. * @return {Promise<void>}
  1905. */
  1906. async _addDeal(ctx, data) {
  1907. if (!data.type || !data.dealBills) throw '数据错误';
  1908. data.dealBills.unit_price = this.ctx.helper.round(data.dealBills.unit_price, ctx.tender.info.decimal.up);
  1909. if (data.dealBills.quantity && data.dealBills.unit) {
  1910. const precision = ctx.helper.findPrecision(ctx.tender.info.precision, data.dealBills.unit);
  1911. data.dealBills.quantity = ctx.helper.round(data.dealBills.quantity, precision.value);
  1912. data.dealBills.sgfh_qty = data.dealBills.quantity;
  1913. data.dealBills.total_price = ctx.helper.mul(data.dealBills.quantity, data.dealBills.unit_price, ctx.tender.info.decimal.tp);
  1914. data.dealBills.sgfh_tp = data.dealBills.total_price;
  1915. }
  1916. if (data.type === 'child') {
  1917. return await ctx.service.changeLedger.addChild(ctx.tender.id, data.id, data.dealBills, ctx.change.cid);
  1918. } else if (data.type === 'next') {
  1919. data.dealBills.ccid = ctx.change.cid;
  1920. return await ctx.service.changeLedger.addNode(ctx.tender.id, data.id, data.dealBills);
  1921. }
  1922. throw '数据错误';
  1923. }
  1924. /**
  1925. * 批量插入数据
  1926. *
  1927. * data = {id, batchData, batchType}
  1928. * data.batchType = 'batchInsertChild'/'batchInsertNext'
  1929. * data.batchData = [{name, children}] -- 项目节列表
  1930. * data.batchData.children = [{code, name, unit, unit_price, quantity}] -- 工程量清单列表
  1931. *
  1932. * @param ctx
  1933. * @return {Promise<void>}
  1934. */
  1935. async _batchInsert(ctx, data) {
  1936. if ((isNaN(data.id) || data.id <= 0) || !data.batchType) throw '参数错误';
  1937. switch (data.batchType) {
  1938. case 'child':
  1939. return await ctx.service.changeLedger.batchInsertChild(ctx.tender.id, data.id, data.batchData);
  1940. case 'next':
  1941. return await ctx.service.changeLedger.batchInsertNext(ctx.tender.id, data.id, data.batchData);
  1942. default:
  1943. throw '参数错误';
  1944. }
  1945. }
  1946. async _updatePos(ctx, data) {
  1947. // await this.checkMeasureType(measureType.tz.value);
  1948. if (!data.posPostType) throw '数据错误';
  1949. switch (data.posPostType) {
  1950. case 'add':
  1951. return await this.ctx.service.changePos.addPos(ctx.tender.id, ctx.change.cid, data.postData);
  1952. case 'update':
  1953. if (data.postData instanceof Array) {
  1954. return await this.ctx.service.changePos.updatePosArr(ctx.tender.id, data.postData);
  1955. }
  1956. return await this.ctx.service.changePos.updatePos(ctx.tender.id, data.postData);
  1957. case 'delete':
  1958. return await this.ctx.service.changePos.deletePos(ctx.tender.id, data.postData);
  1959. case 'paste':
  1960. return await this.ctx.service.changePos.pastePosData(ctx.tender.id, ctx.change.cid, data.postData);
  1961. default:
  1962. throw '未知操作';
  1963. }
  1964. }
  1965. async _filterChangesProject(ctx, status = 0) {
  1966. const tenderId = ctx.params.id;
  1967. ctx.session.sessionUser.tenderId = tenderId;
  1968. const tender = await this.service.tender.getDataById(ctx.tender.id);
  1969. // const tender = ctx.tender;
  1970. // const tenderList = await this.service.tender.getList();
  1971. const page = ctx.page;
  1972. const pageSize = ctx.pageSize;
  1973. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  1974. const orders = ctx.query.order ? ctx.query.order : 0;
  1975. const changes = await ctx.service.changeProject.getListByStatus(tender.id, status, 1, sorts, orders);
  1976. const total = await ctx.service.changeProject.getCountByStatus(tender.id, status);
  1977. for (const c of changes) {
  1978. if (c.status !== audit.change.status.checked || !c.final_auditor_str) {
  1979. c.curAuditors = await ctx.service.changeProjectAudit.getAuditorsByStatus(c.id, c.status, c.times);
  1980. if (c.status === audit.change.status.checked && c.curAuditors.length > 0) {
  1981. const final_auditor_str = c.curAuditors[0].audit_type === auditType.key.common
  1982. ? c.curAuditors[0].name + (c.curAuditors[0].role ? '-' + c.curAuditors[0].role : '')
  1983. : ctx.helper.transFormToChinese(c.curAuditors[0].audit_order) + '审';
  1984. await ctx.service.changeProject.defaultUpdate({ final_auditor_str }, { where: { id: c.id } });
  1985. }
  1986. }
  1987. }
  1988. const accountInfo = await this.ctx.service.projectAccount.getDataById(this.ctx.session.sessionUser.accountId);
  1989. const userPermission = accountInfo !== undefined && accountInfo.permission !== ''
  1990. ? JSON.parse(accountInfo.permission) : null;
  1991. // 分页相关
  1992. const pageInfo = {
  1993. page,
  1994. pageSizeSelect: 1,
  1995. pageSize,
  1996. total_num: total,
  1997. total: Math.ceil(total / pageSize),
  1998. queryData: JSON.stringify(ctx.urlInfo.query),
  1999. };
  2000. const filter = JSON.parse(JSON.stringify(audit.changeProject.filter));
  2001. filter.count = [];
  2002. 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);
  2003. 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);
  2004. 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);
  2005. 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);
  2006. 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);
  2007. let codeRule = [];
  2008. let c_connector = '1';
  2009. let c_rule_first = 1;
  2010. const rule_type = tender.user_id === ctx.session.sessionUser.accountId ? 'suggestion' : 'will';
  2011. if (tender.c_code_rules) {
  2012. const c_code_rules = JSON.parse(tender.c_code_rules);
  2013. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  2014. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  2015. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  2016. }
  2017. for (const rule of codeRule) {
  2018. switch (rule.rule_type) {
  2019. case codeRuleConst.measure.ruleType.dealCode:
  2020. rule.preview = ctx.tender.info.deal_info.dealCode;
  2021. break;
  2022. case codeRuleConst.measure.ruleType.tenderName:
  2023. rule.preview = tender.name;
  2024. break;
  2025. case codeRuleConst.measure.ruleType.inDate:
  2026. rule.preview = moment().format('YYYY');
  2027. break;
  2028. case codeRuleConst.measure.ruleType.text:
  2029. rule.preview = rule.text;
  2030. break;
  2031. case codeRuleConst.measure.ruleType.addNo:
  2032. const s = '0000000000';
  2033. rule.preview = s.substr(s.length - rule.format);
  2034. break;
  2035. default: break;
  2036. }
  2037. }
  2038. const renderData = {
  2039. uid: ctx.session.sessionUser.accountId,
  2040. userPermission,
  2041. tender,
  2042. pageInfo,
  2043. changes,
  2044. status,
  2045. rule_type,
  2046. codeRule,
  2047. c_connector,
  2048. c_rule_first,
  2049. filter,
  2050. ruleType: codeRuleConst.ruleType[rule_type],
  2051. dealCode: ctx.tender.info.deal_info.dealCode,
  2052. auditConst: audit.changeProject,
  2053. ruleConst: codeRuleConst.measure,
  2054. changeConst,
  2055. auditType,
  2056. tenderMenu: this.menu.tenderMenu,
  2057. preUrl: '/tender/' + tender.id,
  2058. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.project),
  2059. };
  2060. await this.layout('change/project.ejs', renderData, 'change/project_modal.ejs');
  2061. }
  2062. /**
  2063. * 变更立项列表 页面 (Get)
  2064. *
  2065. * @param {Object} ctx - egg全局变量
  2066. * @return {void}
  2067. */
  2068. async project(ctx) {
  2069. try {
  2070. await this._filterChangesProject(ctx);
  2071. } catch (err) {
  2072. this.log(err);
  2073. ctx.redirect('/dashboard');
  2074. }
  2075. }
  2076. /**
  2077. * 审批流程(Get)
  2078. * @param ctx
  2079. * @return {Promise<void>}
  2080. */
  2081. async changeProjectAuditors(ctx) {
  2082. try {
  2083. const id = JSON.parse(ctx.request.body.data).id;
  2084. const tenderId = ctx.params.id;
  2085. const changeInfo = await ctx.service.changeProject.getDataById(id);
  2086. await ctx.service.changeProject.loadChangeUser(changeInfo);
  2087. await ctx.service.changeProject.loadChangeAuditViewData(changeInfo);
  2088. ctx.body = { err: 0, msg: '', data: changeInfo };
  2089. } catch (error) {
  2090. this.log(error);
  2091. ctx.body = { err: 1, msg: error.toString(), data: null };
  2092. }
  2093. }
  2094. /**
  2095. * 新增变更立项 (Post)
  2096. *
  2097. * @param {Object} ctx - egg全局变量
  2098. * @return {void}
  2099. */
  2100. async projectAdd(ctx) {
  2101. try {
  2102. const tenderId = ctx.params.id;
  2103. if (!tenderId) {
  2104. throw '当前未打开标段';
  2105. }
  2106. const data = JSON.parse(ctx.request.body.data);
  2107. if (!data.code || data.code === '' || !data.name || data.name === '') {
  2108. throw '变更立项书编号不能为空';
  2109. }
  2110. // 在生成新变更立项后,需要copy前一个变更立项报表的签名信息
  2111. const lastChange = await ctx.service.changeProject.getLastChange(tenderId);
  2112. const change = await ctx.service.changeProject.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.name);
  2113. await ctx.service.roleRptRel.createRoleRelationshipFromOtherBz(tenderId, '-302', change.id, lastChange ? lastChange.id : null);
  2114. ctx.body = { err: 0, msg: '', data: change };
  2115. } catch (err) {
  2116. this.log(err);
  2117. ctx.body = { err: 1, msg: err.toString() };
  2118. }
  2119. }
  2120. /**
  2121. * 删除变更立项
  2122. * @param {Object} ctx - egg全局变量
  2123. * @return {void}
  2124. */
  2125. async projectDelete(ctx) {
  2126. try {
  2127. const result = await ctx.service.changeProject.delete(ctx.request.body.cpid);
  2128. if (!result) {
  2129. throw '删除变更立项失败';
  2130. }
  2131. ctx.redirect(ctx.request.header.referer);
  2132. } catch (err) {
  2133. console.log(err);
  2134. ctx.redirect(ctx.request.header.referer);
  2135. }
  2136. }
  2137. /**
  2138. * 变更管理 状态筛选 页面 (Get)
  2139. * @param {Object} ctx - egg全局变量
  2140. * @return {void}
  2141. */
  2142. async projectStatus(ctx) {
  2143. try {
  2144. const status = parseInt(ctx.params.status);
  2145. await this._filterChangesProject(ctx, status);
  2146. } catch (err) {
  2147. this.logger.error(err);
  2148. ctx.redirect('/tender/' + ctx.params.id + '/change/project');
  2149. }
  2150. }
  2151. /**
  2152. * 获取审批界面所需的 原报、审批人数据等
  2153. * @param ctx
  2154. * @return {Promise<void>}
  2155. * @private
  2156. */
  2157. async _getChangeProjectAuditViewData(ctx) {
  2158. await ctx.service.changeProject.loadChangeAuditViewData(ctx.change);
  2159. }
  2160. // 变更类别获取及更新
  2161. async _getOrUpdateClass(ctx, serviceName) {
  2162. // 工程变更类别读取
  2163. const fun_set = this.ctx.subProject.fun_set;
  2164. if (ctx.change.status === audit[serviceName].status.uncheck ||
  2165. (serviceName === 'changeProject' && ctx.change.status === audit[serviceName].status.back) ||
  2166. (serviceName !== 'changeProject' && ctx.change.status === audit[serviceName].status.checkNo)) {
  2167. const classInfo = ctx.helper._.find(fun_set.change_class, function(item) {
  2168. return item.checked && (item.name === ctx.change.class || item.new_name === ctx.change.class);
  2169. });
  2170. if (!classInfo) {
  2171. const classInfo2 = ctx.helper._.find(fun_set.change_class, { checked: true });
  2172. ctx.change.class = classInfo2.new_name ? classInfo2.new_name : classInfo2.name;
  2173. await ctx.service[serviceName].defaultUpdate({
  2174. id: ctx.change.id,
  2175. class: ctx.change.class,
  2176. });
  2177. } else if (classInfo && classInfo.new_name && ctx.change.class !== classInfo.new_name) {
  2178. ctx.change.class = classInfo.new_name;
  2179. await ctx.service[serviceName].defaultUpdate({
  2180. id: ctx.change.id,
  2181. class: ctx.change.class,
  2182. });
  2183. }
  2184. }
  2185. return fun_set.change_class;
  2186. }
  2187. async projectInformation(ctx) {
  2188. try {
  2189. const whiteList = this.ctx.app.config.multipart.whitelist;
  2190. // const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  2191. // 获取附件列表
  2192. const fileList = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2193. await this._getChangeProjectAuditViewData(ctx);
  2194. const changeClass = await this._getOrUpdateClass(ctx, 'changeProject');
  2195. // 获取用户人验证手机号
  2196. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  2197. const auth_mobile = pa.auth_mobile;
  2198. const userPermission = pa && pa.permission ? JSON.parse(pa.permission) : null;
  2199. const deleteFilePermission = !!(userPermission && userPermission.change !== undefined && userPermission.change.indexOf('2') !== -1);
  2200. // 判断并更新
  2201. const renderData = {
  2202. tender: ctx.tender,
  2203. change: ctx.change,
  2204. changeConst,
  2205. changeClass,
  2206. auditConst: audit.changeProject,
  2207. fileList,
  2208. whiteList,
  2209. authMobile: auth_mobile,
  2210. deleteFilePermission,
  2211. auditType,
  2212. shenpiConst,
  2213. returnUrl: this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/project') ? ctx.request.headers.referer : null,
  2214. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.project_information),
  2215. preUrl: '/tender/' + ctx.tender.id + '/change/project/' + ctx.change.id + '/information',
  2216. };
  2217. // 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)) {
  2218. // data.accountGroup = accountGroup;
  2219. // 获取所有项目参与者
  2220. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  2221. renderData.accountList = accountList;
  2222. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  2223. renderData.accountGroup = unitList.map(item => {
  2224. const groupList = accountList.filter(item1 => item1.company === item.name);
  2225. return { groupName: item.name, groupList };
  2226. }).filter(x => { return x.groupList.length > 0; });
  2227. // 获取固定审批流列表
  2228. if (ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  2229. renderData.spGroupList = await ctx.service.shenpiGroup.getGroupListByChangeType(ctx.tender.id, shenpiConst.sp_type.change, 'changeProject');
  2230. }
  2231. // }
  2232. await this.layout('change/project_information.ejs', renderData, 'change/project_information_modal.ejs');
  2233. } catch (err) {
  2234. this.log(err);
  2235. ctx.redirect('/tender/' + ctx.params.id + '/change/project');
  2236. }
  2237. }
  2238. async changeProjectSpGroup(ctx) {
  2239. try {
  2240. const data = JSON.parse(ctx.request.body.data);
  2241. const result = await ctx.service.changeProjectAudit.changeSpGroup(ctx.change, data.sp_group);
  2242. if (!result) {
  2243. throw '切换审批组失败';
  2244. }
  2245. const auditors = await ctx.service.changeProjectAudit.getUserGroup(ctx.change.id, ctx.change.times);
  2246. ctx.body = { err: 0, msg: '', data: auditors };
  2247. } catch (err) {
  2248. ctx.body = { err: 1, msg: err.toString(), data: null };
  2249. }
  2250. }
  2251. // 审批相关
  2252. /**
  2253. * 添加审批人
  2254. * @param ctx
  2255. * @return {Promise<void>}
  2256. */
  2257. async addProjectAudit(ctx) {
  2258. try {
  2259. const auditConst = audit.changeProject;
  2260. const data = JSON.parse(ctx.request.body.data);
  2261. const id = this.app._.toInteger(data.auditorId);
  2262. if (isNaN(id) || id <= 0) {
  2263. throw '参数错误';
  2264. }
  2265. // 检查权限等
  2266. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2267. throw '您无权添加审核人';
  2268. }
  2269. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2270. throw '当前不允许添加审核人';
  2271. }
  2272. // 判断是否是协审人,是则无法添加到审批人中
  2273. const xsAuditorList = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  2274. const xsAidList = this.app._.map(xsAuditorList, 'aid');
  2275. if (this.app._.indexOf(xsAidList, id) !== -1) {
  2276. throw '该用户已添加到协审人列表中,请删除该协审人再添加';
  2277. }
  2278. ctx.change.auditorList = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  2279. // 检查审核人是否已存在
  2280. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  2281. if (exist) {
  2282. throw '该审核人已存在,请勿重复添加';
  2283. }
  2284. const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdzs });
  2285. const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs ? 1 : 0;
  2286. const result = await ctx.service.changeProjectAudit.addAuditor(ctx.change.id, id, ctx.change.times, is_gdzs);
  2287. if (!result) {
  2288. throw '添加审核人失败';
  2289. }
  2290. const auditors = await ctx.service.changeProjectAudit.getUserGroup(ctx.change.id, ctx.change.times);
  2291. ctx.body = { err: 0, msg: '', data: auditors };
  2292. } catch (err) {
  2293. this.log(err);
  2294. ctx.body = { err: 1, msg: err.toString(), data: null };
  2295. }
  2296. }
  2297. /**
  2298. * 移除审批人
  2299. * @param ctx
  2300. * @return {Promise<void>}
  2301. */
  2302. async deleteProjectAudit(ctx) {
  2303. try {
  2304. const data = JSON.parse(ctx.request.body.data);
  2305. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  2306. if (isNaN(id) || id <= 0) {
  2307. throw '参数错误';
  2308. }
  2309. const result = await ctx.service.changeProjectAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  2310. if (!result) {
  2311. throw '移除审核人失败';
  2312. }
  2313. const auditors = await ctx.service.changeProjectAudit.getAuditors(ctx.change.id, ctx.change.times);
  2314. ctx.body = { err: 0, msg: '', data: auditors };
  2315. } catch (err) {
  2316. ctx.body = { err: 1, msg: err.toString(), data: null };
  2317. }
  2318. }
  2319. /**
  2320. * 添加协审人
  2321. * @param ctx
  2322. * @return {Promise<void>}
  2323. */
  2324. async addProjectXsAudit(ctx) {
  2325. try {
  2326. const auditConst = audit.changeProject;
  2327. const data = JSON.parse(ctx.request.body.data);
  2328. const id = this.app._.toInteger(data.auditorId);
  2329. if (isNaN(id) || id <= 0) {
  2330. throw '参数错误';
  2331. }
  2332. const times = ctx.change.status === auditConst.status.back ? ctx.change.times - 1 : ctx.change.times;
  2333. const spAuditors = await ctx.service.changeProjectAudit.getAuditorsWithOwner(ctx.change.id, times);
  2334. const aidLists = this.app._.map(spAuditors, 'aid');
  2335. // 检查权限等
  2336. if (this.app._.indexOf(aidLists, ctx.session.sessionUser.accountId) === -1) {
  2337. throw '您无权添加协审人';
  2338. }
  2339. // 如果已经是审批人则无法添加此人为协审
  2340. if (this.app._.indexOf(aidLists, id) !== -1) {
  2341. throw '该用户为审批人或原报,无需添加至协审人';
  2342. }
  2343. const auditorList = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  2344. // 检查审核人是否已存在
  2345. const exist = this.app._.find(auditorList, { aid: id });
  2346. if (exist) {
  2347. throw '该协审人已存在,请勿重复添加';
  2348. }
  2349. const result = await ctx.service.changeProjectXsAudit.addAuditor(ctx.change.id, id);
  2350. if (!result) {
  2351. throw '添加协审人失败';
  2352. }
  2353. const auditors = await ctx.service.changeProjectXsAudit.getOneAudit(ctx.change.id, id);
  2354. ctx.body = { err: 0, msg: '', data: auditors };
  2355. } catch (err) {
  2356. this.log(err);
  2357. ctx.body = { err: 1, msg: err.toString(), data: null };
  2358. }
  2359. }
  2360. /**
  2361. * 移除协审人
  2362. * @param ctx
  2363. * @return {Promise<void>}
  2364. */
  2365. async deleteProjectXsAudit(ctx) {
  2366. try {
  2367. const data = JSON.parse(ctx.request.body.data);
  2368. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  2369. if (isNaN(id) || id <= 0) {
  2370. throw '参数错误';
  2371. }
  2372. const result = await ctx.service.changeProjectXsAudit.deleteAuditor(ctx.change.id, id);
  2373. if (!result) {
  2374. throw '移除协审人失败';
  2375. }
  2376. const auditors = await ctx.service.changeProjectXsAudit.getAuditList(ctx.change.id);
  2377. ctx.body = { err: 0, msg: '', data: auditors };
  2378. } catch (err) {
  2379. ctx.body = { err: 1, msg: err.toString(), data: null };
  2380. }
  2381. }
  2382. async saveProjectAudit(ctx) {
  2383. try {
  2384. // if (ctx.change.revising) {
  2385. // throw '台账修订中,请勿修改提交期数据';
  2386. // }
  2387. const data = JSON.parse(ctx.request.body.data);
  2388. if (ctx.session.sessionUser.is_admin && ctx.change.status !== audit.change.status.checked) {
  2389. await ctx.service.changeProjectAudit.saveAudit(ctx.change.id, ctx.change.times, ctx.change.sp_group, data);
  2390. const auditors = await ctx.service.changeProjectAudit.getUniqUserGroup(ctx.change.id, ctx.change.times);
  2391. ctx.body = { err: 0, msg: '', data: auditors };
  2392. } else {
  2393. throw '您无权进行该操作';
  2394. }
  2395. } catch (err) {
  2396. this.log(err);
  2397. // ctx.session.postError = err.toString();
  2398. // ctx.redirect(ctx.request.header.referer);
  2399. ctx.body = {
  2400. err: 1,
  2401. // url: ctx.request.header.referer,
  2402. msg: err,
  2403. };
  2404. }
  2405. }
  2406. /**
  2407. * 上传附件
  2408. * @param {*} ctx 上下文
  2409. */
  2410. async uploadProjectFile(ctx) {
  2411. let stream;
  2412. try {
  2413. const auditConst = audit.changeProject;
  2414. // this._checkAdvanceFileCanModify(ctx);
  2415. const parts = this.ctx.multipart({
  2416. autoFields: true,
  2417. });
  2418. const files = [];
  2419. const create_time = Date.parse(new Date()) / 1000;
  2420. let idx = 0;
  2421. const extra_upload = ctx.change.status === auditConst.status.checked;
  2422. while ((stream = await parts()) !== undefined) {
  2423. if (!stream.filename) {
  2424. // 如果没有传入直接返回
  2425. return;
  2426. }
  2427. const fileInfo = path.parse(stream.filename);
  2428. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_project/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  2429. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  2430. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  2431. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  2432. ++idx;
  2433. stream && (await sendToWormhole(stream));
  2434. }
  2435. const in_time = new Date();
  2436. const payload = files.map(file => {
  2437. let idx;
  2438. if (Array.isArray(parts.field.name)) {
  2439. idx = parts.field.name.findIndex(name => name === file.name);
  2440. } else {
  2441. idx = 'isString';
  2442. }
  2443. const newFile = {
  2444. tid: ctx.tender.id,
  2445. cpid: ctx.change.id,
  2446. uid: ctx.session.sessionUser.accountId,
  2447. filename: file.name,
  2448. fileext: file.ext,
  2449. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  2450. filepath: file.filepath,
  2451. upload_time: in_time,
  2452. extra_upload,
  2453. };
  2454. return newFile;
  2455. });
  2456. // 执行文件信息写入数据库
  2457. await ctx.service.changeProjectAtt.saveFileMsgToDb(payload);
  2458. // 将最新的当前标段的所有文件信息返回
  2459. const data = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2460. ctx.body = { err: 0, msg: '', data };
  2461. } catch (err) {
  2462. stream && (await sendToWormhole(stream));
  2463. this.log(err);
  2464. ctx.body = { err: 1, msg: err.toString(), data: null };
  2465. }
  2466. }
  2467. /**
  2468. * 删除附件
  2469. * @param {Ojbect} ctx 上下文
  2470. */
  2471. async deleteProjectFile(ctx) {
  2472. try {
  2473. const { id } = JSON.parse(ctx.request.body.data);
  2474. const fileInfo = await ctx.service.changeProjectAtt.getDataById(id);
  2475. if (fileInfo || Object.keys(fileInfo).length) {
  2476. // 先删除文件
  2477. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  2478. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  2479. // 再删除数据库
  2480. await ctx.service.changeProjectAtt.delete(id);
  2481. } else {
  2482. throw '不存在该文件';
  2483. }
  2484. const data = await ctx.service.changeProjectAtt.getAllChangeProjectAtt(ctx.tender.id, ctx.change.id);
  2485. ctx.body = { err: 0, msg: '请求成功', data };
  2486. } catch (err) {
  2487. this.log(err);
  2488. ctx.body = { err: 1, msg: err.toString(), data: null };
  2489. }
  2490. }
  2491. /**
  2492. * 下载附件
  2493. * @param {Object} ctx - egg全局变量
  2494. * @return {void}
  2495. */
  2496. async downloadProjectFile(ctx) {
  2497. const id = ctx.params.fid;
  2498. if (id) {
  2499. try {
  2500. const fileInfo = await ctx.service.changeProjectAtt.getDataById(id);
  2501. if (fileInfo !== undefined && fileInfo !== '') {
  2502. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  2503. // 解决中文无法下载问题
  2504. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  2505. let disposition = '';
  2506. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  2507. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  2508. } else if (userAgent.indexOf('firefox') >= 0) {
  2509. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  2510. } else {
  2511. /* safari等其他非主流浏览器只能自求多福了 */
  2512. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  2513. }
  2514. ctx.response.set({
  2515. 'Content-Type': 'application/octet-stream',
  2516. 'Content-Disposition': disposition,
  2517. 'Content-Length': fileInfo.filesize,
  2518. });
  2519. // ctx.body = await fs.createReadStream(fileName);
  2520. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  2521. } else {
  2522. throw '不存在该文件';
  2523. }
  2524. } catch (err) {
  2525. this.log(err);
  2526. this.setMessage(err.toString(), this.messageType.ERROR);
  2527. }
  2528. }
  2529. }
  2530. async projectInformationSave(ctx) {
  2531. try {
  2532. const data = JSON.parse(ctx.request.body.data);
  2533. if (data.name === 'code') {
  2534. const info = await ctx.service.changeProject.isRepeat(ctx.change.id, data.val, ctx.tender.id, ctx.change.type);
  2535. if (info) {
  2536. throw '该编号已存在';
  2537. }
  2538. }
  2539. const result = await ctx.service.changeProject.saveInfo(ctx.change.id, data);
  2540. if (!result) {
  2541. throw '修改失败';
  2542. }
  2543. ctx.body = { err: 0, msg: '请求成功', data: null };
  2544. } catch (err) {
  2545. this.log(err);
  2546. ctx.body = { err: 1, msg: err.toString(), data: null };
  2547. }
  2548. }
  2549. /**
  2550. * 上报和重新上报
  2551. * @param ctx
  2552. * @return {Promise<void>}
  2553. */
  2554. async startProjectAudit(ctx) {
  2555. try {
  2556. const auditConst = audit.changeProject;
  2557. // 检查权限等
  2558. if (!ctx.change) {
  2559. throw '数据错误';
  2560. }
  2561. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  2562. throw '您无权上报该变更立项数据';
  2563. }
  2564. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  2565. throw '该变更立项数据当前无法上报';
  2566. }
  2567. await ctx.service.changeProjectAudit.start(ctx.change.id, ctx.change.times);
  2568. ctx.redirect(ctx.request.header.referer);
  2569. } catch (err) {
  2570. this.log(err);
  2571. ctx.session.postError = err.toString();
  2572. ctx.redirect(ctx.request.header.referer);
  2573. }
  2574. }
  2575. /**
  2576. * 审批
  2577. * @param ctx
  2578. * @return {Promise<void>}
  2579. */
  2580. async checkProjectAudit(ctx) {
  2581. try {
  2582. const auditConst = audit.changeProject;
  2583. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  2584. throw '当前变更立项数据有误';
  2585. }
  2586. if (ctx.change.curAuditorIds.length === 0 || ctx.change.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  2587. throw '您无权进行该操作';
  2588. }
  2589. const data = {
  2590. checkType: parseInt(ctx.request.body.checkType),
  2591. opinion: ctx.request.body.opinion,
  2592. };
  2593. if (!data.checkType || isNaN(data.checkType)) {
  2594. throw '提交数据错误';
  2595. }
  2596. // if (data.checkType === auditConst.status.checkNo) {
  2597. // if (!data.checkType || isNaN(data.checkType)) {
  2598. // throw '提交数据错误';
  2599. // }
  2600. // }
  2601. await ctx.service.changeProjectAudit.check(ctx.change.id, data, ctx.change.times);
  2602. ctx.redirect(ctx.request.header.referer);
  2603. } catch (err) {
  2604. this.log(err);
  2605. ctx.session.postError = err.toString();
  2606. ctx.redirect(ctx.request.header.referer);
  2607. }
  2608. }
  2609. /**
  2610. * 撤回审批
  2611. * @param ctx
  2612. * @return {Promise<void>}
  2613. */
  2614. async checkProjectAuditCancel(ctx) {
  2615. try {
  2616. if (!ctx.change.cancancel) throw '您无权进行该操作';
  2617. await ctx.service.changeProjectAudit.checkCancel(ctx.change);
  2618. ctx.body = { err: 0, url: ctx.request.header.referer, msg: '' };
  2619. } catch (err) {
  2620. this.log(err);
  2621. ctx.body = { err: 1, msg: err };
  2622. }
  2623. }
  2624. /**
  2625. * 变更立项重新审批
  2626. * @param {Object} ctx - egg全局变量
  2627. * @return {void}
  2628. */
  2629. async checkProjectAgain(ctx) {
  2630. try {
  2631. // 获取终审
  2632. // const auditInfo = await this.ctx.service.changeProjectAudit.getAuditorByStatus(ctx.change.id, audit.changeProject.status.checked);
  2633. // if (ctx.change.status !== audit.changeProject.status.checked || ctx.session.sessionUser.accountId !== auditInfo.aid) {
  2634. if (ctx.change.status !== audit.changeProject.status.checked) {
  2635. throw '您无权进行该操作';
  2636. }
  2637. // 判断是否被变更申请调用了,是则无法发起修订
  2638. const projectInfo = await ctx.service.changeApply.getDataByCondition({ tid: ctx.tender.id, project_code: ctx.change.code });
  2639. if (projectInfo) {
  2640. throw '该变更立项已被变更申请调用,无法发起重新审批';
  2641. }
  2642. if (ctx.session.sessionUser.loginStatus === 0) {
  2643. const code = ctx.request.body.code;
  2644. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  2645. if (!pa.auth_mobile) {
  2646. throw '未绑定手机号';
  2647. }
  2648. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  2649. const cacheCode = await app.redis.get(cacheKey);
  2650. // console.log(cacheCode);
  2651. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  2652. throw '验证码不正确!';
  2653. }
  2654. }
  2655. if ((ctx.change.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0) && ctx.change.status === audit.changeProject.status.checked) {
  2656. // 重新审批
  2657. const result = await ctx.service.changeProjectAudit.checkAgain(ctx.change);
  2658. if (!result) {
  2659. throw '重新审批失败';
  2660. }
  2661. } else {
  2662. throw '您无权进行该操作';
  2663. }
  2664. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  2665. ctx.body = {
  2666. err: 0,
  2667. url: ctx.request.header.referer,
  2668. msg: '',
  2669. };
  2670. } catch (err) {
  2671. console.log(err);
  2672. // ctx.redirect(ctx.request.header.referer);
  2673. ctx.body = {
  2674. err: 1,
  2675. // url: ctx.request.header.referer,
  2676. msg: err,
  2677. };
  2678. }
  2679. }
  2680. /**
  2681. * 变更立项修订重新上报
  2682. * @param {Object} ctx - egg全局变量
  2683. * @return {void}
  2684. */
  2685. async checkProjectRevise(ctx) {
  2686. try {
  2687. if (ctx.change.status !== audit.changeProject.status.checked || ctx.session.sessionUser.accountId !== ctx.change.uid) {
  2688. throw '您无权进行该操作';
  2689. }
  2690. // 判断是否被变更申请调用了,是则无法发起修订
  2691. const projectInfo = await ctx.service.changeApply.getDataByCondition({ tid: ctx.tender.id, project_code: ctx.change.code });
  2692. if (projectInfo) {
  2693. throw '该变更立项已被变更申请调用,无法发起修订';
  2694. }
  2695. if (ctx.session.sessionUser.loginStatus === 0) {
  2696. const code = ctx.request.body.code;
  2697. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  2698. if (!pa.auth_mobile) {
  2699. throw '未绑定手机号';
  2700. }
  2701. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  2702. const cacheCode = await app.redis.get(cacheKey);
  2703. // console.log(cacheCode);
  2704. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  2705. throw '验证码不正确!';
  2706. }
  2707. }
  2708. // 重新审批
  2709. const result = await ctx.service.changeProjectAudit.checkRevise(ctx.change);
  2710. if (!result) {
  2711. throw '修订发起失败';
  2712. }
  2713. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  2714. ctx.body = {
  2715. err: 0,
  2716. url: ctx.request.header.referer,
  2717. msg: '',
  2718. };
  2719. } catch (err) {
  2720. console.log(err);
  2721. // ctx.redirect(ctx.request.header.referer);
  2722. ctx.body = {
  2723. err: 1,
  2724. // url: ctx.request.header.referer,
  2725. msg: err,
  2726. };
  2727. }
  2728. }
  2729. /**
  2730. * 变更令撤销修订
  2731. * @param {Object} ctx - egg全局变量
  2732. * @return {void}
  2733. */
  2734. async cancelProjectRevise(ctx) {
  2735. try {
  2736. if (!(ctx.change.status === audit.changeProject.status.revise && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.session.sessionUser.accountId === ctx.session.sessionUser.is_admin))) {
  2737. throw '您无权进行该操作';
  2738. }
  2739. // 重新审批
  2740. const result = await ctx.service.changeProjectAudit.cancelRevise(ctx.change);
  2741. if (!result) {
  2742. throw '撤销修订失败';
  2743. }
  2744. ctx.body = {
  2745. err: 0,
  2746. url: ctx.request.header.referer,
  2747. msg: '',
  2748. };
  2749. } catch (err) {
  2750. console.log(err);
  2751. ctx.body = {
  2752. err: 1,
  2753. msg: err,
  2754. };
  2755. }
  2756. }
  2757. async _filterChangesApply(ctx, status = 0) {
  2758. const tenderId = ctx.params.id;
  2759. ctx.session.sessionUser.tenderId = tenderId;
  2760. const tender = await this.service.tender.getDataById(ctx.tender.id);
  2761. // const tender = ctx.tender;
  2762. // const tenderList = await this.service.tender.getList();
  2763. const page = ctx.page;
  2764. const pageSize = ctx.pageSize;
  2765. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  2766. const orders = ctx.query.order ? ctx.query.order : 0;
  2767. const changes = await ctx.service.changeApply.getListByStatus(tender.id, status, 1, sorts, orders);
  2768. const total = await ctx.service.changeApply.getCountByStatus(tender.id, status);
  2769. let page_total = 0;
  2770. const tp = await ctx.service.changeApply.getTp(tender.id, status);
  2771. for (const c of changes) {
  2772. if (c.status !== audit.change.status.checked || !c.final_auditor_str) {
  2773. c.curAuditors = await ctx.service.changeApplyAudit.getAuditorsByStatus(c.id, c.status, c.times);
  2774. if (c.status === audit.change.status.checked && c.curAuditors.length > 0) {
  2775. const final_auditor_str = c.curAuditors[0].audit_type === auditType.key.common
  2776. ? c.curAuditors[0].name + (c.curAuditors[0].role ? '-' + c.curAuditors[0].role : '')
  2777. : ctx.helper.transFormToChinese(c.curAuditors[0].audit_order) + '审';
  2778. await ctx.service.changeApply.defaultUpdate({ final_auditor_str }, { where: { id: c.id } });
  2779. }
  2780. }
  2781. page_total = ctx.helper.add(page_total, c.total_price);
  2782. }
  2783. const tender_userInfo = await ctx.service.projectAccount.getDataById(ctx.tender.data.user_id);
  2784. // 分页相关
  2785. const pageInfo = {
  2786. page,
  2787. pageSizeSelect: 1,
  2788. pageSize,
  2789. total_num: total,
  2790. total: Math.ceil(total / pageSize),
  2791. queryData: JSON.stringify(ctx.urlInfo.query),
  2792. };
  2793. const filter = JSON.parse(JSON.stringify(audit.changeApply.filter));
  2794. filter.count = [];
  2795. 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);
  2796. 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);
  2797. 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);
  2798. 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);
  2799. // 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);
  2800. let codeRule = [];
  2801. let c_connector = '1';
  2802. let c_rule_first = 1;
  2803. const rule_type = 'apply';
  2804. if (tender.c_code_rules) {
  2805. const c_code_rules = JSON.parse(tender.c_code_rules);
  2806. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  2807. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  2808. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  2809. }
  2810. for (const rule of codeRule) {
  2811. switch (rule.rule_type) {
  2812. case codeRuleConst.measure.ruleType.dealCode:
  2813. rule.preview = ctx.tender.info.deal_info.dealCode;
  2814. break;
  2815. case codeRuleConst.measure.ruleType.tenderName:
  2816. rule.preview = tender.name;
  2817. break;
  2818. case codeRuleConst.measure.ruleType.inDate:
  2819. rule.preview = moment().format('YYYY');
  2820. break;
  2821. case codeRuleConst.measure.ruleType.text:
  2822. rule.preview = rule.text;
  2823. break;
  2824. case codeRuleConst.measure.ruleType.addNo:
  2825. const s = '0000000000';
  2826. rule.preview = s.substr(s.length - rule.format);
  2827. break;
  2828. default: break;
  2829. }
  2830. }
  2831. const changeProjectList = await ctx.service.changeProject.getAllDataByCondition({ where: { tid: tender.id, status: audit.changeProject.status.checked } });
  2832. const allProjectCodes = await ctx.service.changeApply.getAllDataByCondition({
  2833. columns: ['project_code'],
  2834. where: {
  2835. tid: tender.id,
  2836. },
  2837. });
  2838. const pcLists = allProjectCodes.length > 0 ? ctx.app._.uniq(ctx.app._.map(allProjectCodes, 'project_code')) : [];
  2839. const renderData = {
  2840. uid: ctx.session.sessionUser.accountId,
  2841. tender,
  2842. pageInfo,
  2843. changes,
  2844. status,
  2845. rule_type,
  2846. codeRule,
  2847. c_connector,
  2848. c_rule_first,
  2849. filter,
  2850. apply_username: tender_userInfo ? tender_userInfo.name : null,
  2851. ruleType: codeRuleConst.ruleType[rule_type],
  2852. dealCode: ctx.tender.info.deal_info.dealCode,
  2853. auditConst: audit.changeApply,
  2854. ruleConst: codeRuleConst.measure,
  2855. changeConst,
  2856. auditType,
  2857. changeProjectList,
  2858. pcLists,
  2859. tp,
  2860. page_total,
  2861. tenderMenu: this.menu.tenderMenu,
  2862. preUrl: '/tender/' + tender.id,
  2863. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply),
  2864. };
  2865. await this.layout('change/apply.ejs', renderData, 'change/apply_modal.ejs');
  2866. }
  2867. /**
  2868. * 变更申请列表 页面 (Get)
  2869. *
  2870. * @param {Object} ctx - egg全局变量
  2871. * @return {void}
  2872. */
  2873. async apply(ctx) {
  2874. try {
  2875. await this._filterChangesApply(ctx);
  2876. } catch (err) {
  2877. this.log(err);
  2878. ctx.redirect('/dashboard');
  2879. }
  2880. }
  2881. /**
  2882. * 变更管理 状态筛选 页面 (Get)
  2883. * @param {Object} ctx - egg全局变量
  2884. * @return {void}
  2885. */
  2886. async applyStatus(ctx) {
  2887. try {
  2888. const status = parseInt(ctx.params.status);
  2889. await this._filterChangesApply(ctx, status);
  2890. } catch (err) {
  2891. this.logger.error(err);
  2892. ctx.redirect('/tender/' + ctx.params.id + '/change/apply');
  2893. }
  2894. }
  2895. /**
  2896. * 审批流程(Get)
  2897. * @param ctx
  2898. * @return {Promise<void>}
  2899. */
  2900. async changeApplyAuditors(ctx) {
  2901. try {
  2902. const id = JSON.parse(ctx.request.body.data).id;
  2903. const tenderId = ctx.params.id;
  2904. const changeInfo = await ctx.service.changeApply.getDataById(id);
  2905. await ctx.service.changeApply.loadChangeUser(changeInfo);
  2906. await ctx.service.changeApply.loadChangeAuditViewData(changeInfo);
  2907. ctx.body = { err: 0, msg: '', data: changeInfo };
  2908. } catch (error) {
  2909. this.log(error);
  2910. ctx.body = { err: 1, msg: error.toString(), data: null };
  2911. }
  2912. }
  2913. async changeApplySpGroup(ctx) {
  2914. try {
  2915. const data = JSON.parse(ctx.request.body.data);
  2916. const result = await ctx.service.changeApplyAudit.changeSpGroup(ctx.change, data.sp_group);
  2917. if (!result) {
  2918. throw '切换审批组失败';
  2919. }
  2920. const auditors = await ctx.service.changeApplyAudit.getUserGroup(ctx.change.id, ctx.change.times);
  2921. ctx.body = { err: 0, msg: '', data: auditors };
  2922. } catch (err) {
  2923. ctx.body = { err: 1, msg: err.toString(), data: null };
  2924. }
  2925. }
  2926. /**
  2927. * 撤回审批
  2928. * @param ctx
  2929. * @return {Promise<void>}
  2930. */
  2931. async checkApplyAuditCancel(ctx) {
  2932. try {
  2933. if (!ctx.change.cancancel) throw '您无权进行该操作';
  2934. await ctx.service.changeApplyAudit.checkCancel(ctx.change);
  2935. ctx.body = { err: 0, url: ctx.request.header.referer, msg: '' };
  2936. } catch (err) {
  2937. this.log(err);
  2938. ctx.body = { err: 1, msg: err };
  2939. }
  2940. }
  2941. /**
  2942. * 新增变更申请 (Post)
  2943. *
  2944. * @param {Object} ctx - egg全局变量
  2945. * @return {void}
  2946. */
  2947. async applyAdd(ctx) {
  2948. try {
  2949. const tenderId = ctx.params.id;
  2950. if (!tenderId) {
  2951. throw '当前未打开标段';
  2952. }
  2953. const data = JSON.parse(ctx.request.body.data);
  2954. if (!data.code || data.code === '') {
  2955. throw '变更申请编号不能为空';
  2956. }
  2957. // 在生成新变更申请后,需要copy前一个变更申请报表的签名信息
  2958. const lastChange = await ctx.service.changeApply.getLastChange(tenderId);
  2959. const change = await ctx.service.changeApply.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.project_code, data.name);
  2960. await ctx.service.roleRptRel.createRoleRelationshipFromOtherBz(tenderId, '-303', change.id, lastChange ? lastChange.id : null);
  2961. ctx.body = { err: 0, msg: '', data: change };
  2962. } catch (err) {
  2963. this.log(err);
  2964. ctx.body = { err: 1, msg: err.toString() };
  2965. }
  2966. }
  2967. /**
  2968. * 删除变更立项
  2969. * @param {Object} ctx - egg全局变量
  2970. * @return {void}
  2971. */
  2972. async applyDelete(ctx) {
  2973. try {
  2974. const result = await ctx.service.changeApply.delete(ctx.request.body.caid);
  2975. if (!result) {
  2976. throw '删除变更立项失败';
  2977. }
  2978. ctx.redirect(ctx.request.header.referer);
  2979. } catch (err) {
  2980. console.log(err);
  2981. ctx.redirect(ctx.request.header.referer);
  2982. }
  2983. }
  2984. /**
  2985. * 获取审批界面所需的 原报、审批人数据等
  2986. * @param ctx
  2987. * @return {Promise<void>}
  2988. * @private
  2989. */
  2990. async _getChangeApplyAuditViewData(ctx) {
  2991. await ctx.service.changeApply.loadChangeAuditViewData(ctx.change);
  2992. }
  2993. async applyInformation(ctx) {
  2994. try {
  2995. const whiteList = this.ctx.app.config.multipart.whitelist;
  2996. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  2997. await this._getChangeApplyAuditViewData(ctx);
  2998. // 获取清单列表
  2999. const changeList = await ctx.service.changeApplyList.getList(ctx.change.id);
  3000. // 获取附件列表
  3001. const fileList = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  3002. const changeClass = await this._getOrUpdateClass(ctx, 'changeApply');
  3003. // 获取用户人验证手机号
  3004. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3005. const auth_mobile = pa.auth_mobile;
  3006. const userPermission = pa && pa.permission ? JSON.parse(pa.permission) : null;
  3007. const deleteFilePermission = !!(userPermission && userPermission.change !== undefined && userPermission.change.indexOf('2') !== -1);
  3008. const renderData = {
  3009. tender,
  3010. change: ctx.change,
  3011. listRule: tender.c_apply_list_rule ? JSON.parse(tender.c_apply_list_rule) : { source: 1, rule: ['unit', 'unit_price'] },
  3012. changeList,
  3013. changeConst,
  3014. changeClass,
  3015. auditConst: audit.changeApply,
  3016. fileList,
  3017. whiteList,
  3018. authMobile: auth_mobile,
  3019. deleteFilePermission,
  3020. auditType,
  3021. shenpiConst,
  3022. tpUnit: ctx.change.decimal ? ctx.change.decimal.tp : ctx.tender.info.decimal.tp,
  3023. upUnit: ctx.change.decimal ? ctx.change.decimal.up : ctx.tender.info.decimal.up,
  3024. changeUnits: changeConst.units,
  3025. precision: ctx.change.decimal && ctx.change.decimal.precision ? ctx.change.decimal.precision : ctx.tender.info.precision,
  3026. returnUrl: this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/apply') && !this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/apply/' + ctx.change.id + '/information') ? ctx.request.headers.referer : null,
  3027. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply_information),
  3028. preUrl: '/tender/' + ctx.tender.id + '/change/apply/' + ctx.change.id + '/information',
  3029. };
  3030. // if ((ctx.change.status === audit.changeApply.status.uncheck || ctx.change.status === audit.changeApply.status.checkNo || ctx.change.status === audit.changeApply.status.revise) && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.tender.isTourist)) {
  3031. // data.accountGroup = accountGroup;
  3032. // 获取所有项目参与者
  3033. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  3034. renderData.accountList = accountList;
  3035. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  3036. renderData.accountGroup = unitList.map(item => {
  3037. const groupList = accountList.filter(item1 => item1.company === item.name);
  3038. return { groupName: item.name, groupList };
  3039. }).filter(x => { return x.groupList.length > 0; });
  3040. // }
  3041. // 获取固定审批流列表
  3042. if (ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  3043. renderData.spGroupList = await ctx.service.shenpiGroup.getGroupListByChangeType(ctx.tender.id, shenpiConst.sp_type.change, 'changeApply');
  3044. }
  3045. await this.layout('change/apply_information.ejs', renderData, 'change/apply_information_modal.ejs');
  3046. } catch (err) {
  3047. this.log(err);
  3048. ctx.redirect('/tender/' + ctx.params.id + '/change/apply');
  3049. }
  3050. }
  3051. async applyInformationNotice(ctx) {
  3052. try {
  3053. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  3054. // 获取附件列表
  3055. const fileList = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  3056. await this._getChangeApplyAuditViewData(ctx);
  3057. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3058. const userPermission = pa && pa.permission ? JSON.parse(pa.permission) : null;
  3059. const deleteFilePermission = !!(userPermission && userPermission.change !== undefined && userPermission.change.indexOf('2') !== -1);
  3060. const renderData = {
  3061. tender,
  3062. change: ctx.change,
  3063. changeConst,
  3064. auditConst: audit.changeApply,
  3065. fileList,
  3066. returnUrl: this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/apply') ? ctx.request.headers.referer : null,
  3067. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.apply_information_notice),
  3068. preUrl: '/tender/' + ctx.tender.id + '/change/apply/' + ctx.change.id + '/information/notice',
  3069. deleteFilePermission,
  3070. };
  3071. await this.layout('change/apply_information_notice.ejs', renderData, 'change/apply_information_notice_modal.ejs');
  3072. } catch (err) {
  3073. this.log(err);
  3074. ctx.redirect('/tender/' + ctx.params.id + '/change');
  3075. }
  3076. }
  3077. // 审批相关
  3078. /**
  3079. * 添加审批人
  3080. * @param ctx
  3081. * @return {Promise<void>}
  3082. */
  3083. async addApplyAudit(ctx) {
  3084. try {
  3085. const auditConst = audit.changeApply;
  3086. const data = JSON.parse(ctx.request.body.data);
  3087. const id = this.app._.toInteger(data.auditorId);
  3088. if (isNaN(id) || id <= 0) {
  3089. throw '参数错误';
  3090. }
  3091. // 检查权限等
  3092. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  3093. throw '您无权添加审核人';
  3094. }
  3095. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  3096. throw '当前不允许添加审核人';
  3097. }
  3098. ctx.change.auditorList = await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, ctx.change.times);
  3099. // 检查审核人是否已存在
  3100. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  3101. if (exist) {
  3102. throw '该审核人已存在,请勿重复添加';
  3103. }
  3104. // const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.material, sp_status: shenpiConst.sp_status.gdzs });
  3105. // const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs ? 1 : 0;
  3106. const result = await ctx.service.changeApplyAudit.addAuditor(ctx.change.id, id, ctx.change.times);
  3107. if (!result) {
  3108. throw '添加审核人失败';
  3109. }
  3110. const auditors = await ctx.service.changeApplyAudit.getUserGroup(ctx.change.id, ctx.change.times);
  3111. ctx.body = { err: 0, msg: '', data: auditors };
  3112. } catch (err) {
  3113. this.log(err);
  3114. ctx.body = { err: 1, msg: err.toString(), data: null };
  3115. }
  3116. }
  3117. /**
  3118. * 移除审批人
  3119. * @param ctx
  3120. * @return {Promise<void>}
  3121. */
  3122. async deleteApplyAudit(ctx) {
  3123. try {
  3124. const data = JSON.parse(ctx.request.body.data);
  3125. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  3126. if (isNaN(id) || id <= 0) {
  3127. throw '参数错误';
  3128. }
  3129. const result = await ctx.service.changeApplyAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  3130. if (!result) {
  3131. throw '移除审核人失败';
  3132. }
  3133. const auditors = await ctx.service.changeApplyAudit.getAuditors(ctx.change.id, ctx.change.times);
  3134. ctx.body = { err: 0, msg: '', data: auditors };
  3135. } catch (err) {
  3136. ctx.body = { err: 1, msg: err.toString(), data: null };
  3137. }
  3138. }
  3139. async saveApplyAudit(ctx) {
  3140. try {
  3141. // if (ctx.change.revising) {
  3142. // throw '台账修订中,请勿修改提交期数据';
  3143. // }
  3144. const data = JSON.parse(ctx.request.body.data);
  3145. if (ctx.session.sessionUser.is_admin && ctx.change.status !== audit.change.status.checked) {
  3146. await ctx.service.changeApplyAudit.saveAudit(ctx.change.id, ctx.change.times, ctx.change.sp_group, data);
  3147. const auditors = await ctx.service.changeApplyAudit.getUniqUserGroup(ctx.change.id, ctx.change.times);
  3148. ctx.body = { err: 0, msg: '', data: auditors };
  3149. } else {
  3150. throw '您无权进行该操作';
  3151. }
  3152. } catch (err) {
  3153. this.log(err);
  3154. // ctx.session.postError = err.toString();
  3155. // ctx.redirect(ctx.request.header.referer);
  3156. ctx.body = {
  3157. err: 1,
  3158. // url: ctx.request.header.referer,
  3159. msg: err,
  3160. };
  3161. }
  3162. }
  3163. /**
  3164. * 上传附件
  3165. * @param {*} ctx 上下文
  3166. */
  3167. async uploadApplyFile(ctx) {
  3168. let stream;
  3169. try {
  3170. const auditConst = audit.changeApply;
  3171. // this._checkAdvanceFileCanModify(ctx);
  3172. const parts = this.ctx.multipart({
  3173. autoFields: true,
  3174. });
  3175. const files = [];
  3176. const create_time = Date.parse(new Date()) / 1000;
  3177. let idx = 0;
  3178. const extra_upload = ctx.change.status === auditConst.status.checked;
  3179. while ((stream = await parts()) !== undefined) {
  3180. if (!stream.filename) {
  3181. // 如果没有传入直接返回
  3182. return;
  3183. }
  3184. const fileInfo = path.parse(stream.filename);
  3185. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_apply/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  3186. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  3187. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  3188. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  3189. ++idx;
  3190. stream && (await sendToWormhole(stream));
  3191. }
  3192. const in_time = new Date();
  3193. const payload = files.map(file => {
  3194. let idx;
  3195. if (Array.isArray(parts.field.name)) {
  3196. idx = parts.field.name.findIndex(name => name === file.name);
  3197. } else {
  3198. idx = 'isString';
  3199. }
  3200. const newFile = {
  3201. tid: ctx.tender.id,
  3202. caid: ctx.change.id,
  3203. uid: ctx.session.sessionUser.accountId,
  3204. type: parts.field.type,
  3205. filename: file.name,
  3206. fileext: file.ext,
  3207. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  3208. filepath: file.filepath,
  3209. upload_time: in_time,
  3210. extra_upload,
  3211. };
  3212. return newFile;
  3213. });
  3214. // 执行文件信息写入数据库
  3215. await ctx.service.changeApplyAtt.saveFileMsgToDb(payload);
  3216. // 将最新的当前标段的所有文件信息返回
  3217. const data = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  3218. ctx.body = { err: 0, msg: '', data };
  3219. } catch (err) {
  3220. stream && (await sendToWormhole(stream));
  3221. this.log(err);
  3222. ctx.body = { err: 1, msg: err.toString(), data: null };
  3223. }
  3224. }
  3225. /**
  3226. * 删除附件
  3227. * @param {Ojbect} ctx 上下文
  3228. */
  3229. async deleteApplyFile(ctx) {
  3230. try {
  3231. const { id } = JSON.parse(ctx.request.body.data);
  3232. const fileInfo = await ctx.service.changeApplyAtt.getDataById(id);
  3233. if (fileInfo || Object.keys(fileInfo).length) {
  3234. // 先删除文件
  3235. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  3236. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  3237. // 再删除数据库
  3238. await ctx.service.changeApplyAtt.delete(id);
  3239. } else {
  3240. throw '不存在该文件';
  3241. }
  3242. const data = await ctx.service.changeApplyAtt.getAllChangeApplyAtt(ctx.tender.id, ctx.change.id);
  3243. ctx.body = { err: 0, msg: '请求成功', data };
  3244. } catch (err) {
  3245. this.log(err);
  3246. ctx.body = { err: 1, msg: err.toString(), data: null };
  3247. }
  3248. }
  3249. /**
  3250. * 下载附件
  3251. * @param {Object} ctx - egg全局变量
  3252. * @return {void}
  3253. */
  3254. async downloadApplyFile(ctx) {
  3255. const id = ctx.params.fid;
  3256. if (id) {
  3257. try {
  3258. const fileInfo = await ctx.service.changeApplyAtt.getDataById(id);
  3259. if (fileInfo !== undefined && fileInfo !== '') {
  3260. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  3261. // 解决中文无法下载问题
  3262. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  3263. let disposition = '';
  3264. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  3265. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  3266. } else if (userAgent.indexOf('firefox') >= 0) {
  3267. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  3268. } else {
  3269. /* safari等其他非主流浏览器只能自求多福了 */
  3270. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  3271. }
  3272. ctx.response.set({
  3273. 'Content-Type': 'application/octet-stream',
  3274. 'Content-Disposition': disposition,
  3275. 'Content-Length': fileInfo.filesize,
  3276. });
  3277. // ctx.body = await fs.createReadStream(fileName);
  3278. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  3279. } else {
  3280. throw '不存在该文件';
  3281. }
  3282. } catch (err) {
  3283. this.log(err);
  3284. this.setMessage(err.toString(), this.messageType.ERROR);
  3285. }
  3286. }
  3287. }
  3288. async applyInformationSave(ctx) {
  3289. try {
  3290. const data = JSON.parse(ctx.request.body.data);
  3291. if (data.name === 'code') {
  3292. const info = await ctx.service.changeApply.isRepeat(ctx.change.id, data.val, ctx.tender.id);
  3293. if (info) {
  3294. throw '该编号已存在';
  3295. }
  3296. }
  3297. const result = await ctx.service.changeApply.saveInfo(ctx.change.id, data);
  3298. if (!result) {
  3299. throw '修改失败';
  3300. }
  3301. ctx.body = { err: 0, msg: '请求成功', data: null };
  3302. } catch (err) {
  3303. this.log(err);
  3304. ctx.body = { err: 1, msg: err.toString(), data: null };
  3305. }
  3306. }
  3307. /**
  3308. * 上报和重新上报
  3309. * @param ctx
  3310. * @return {Promise<void>}
  3311. */
  3312. async startApplyAudit(ctx) {
  3313. try {
  3314. const auditConst = audit.changeApply;
  3315. // 检查权限等
  3316. if (!ctx.change) {
  3317. throw '数据错误';
  3318. }
  3319. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  3320. throw '您无权上报该变更申请数据';
  3321. }
  3322. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  3323. throw '该变更申请数据当前无法上报';
  3324. }
  3325. await ctx.service.changeApplyAudit.start(ctx.change.id, ctx.change.times);
  3326. ctx.redirect(ctx.request.header.referer);
  3327. } catch (err) {
  3328. this.log(err);
  3329. ctx.session.postError = err.toString();
  3330. ctx.redirect(ctx.request.header.referer);
  3331. }
  3332. }
  3333. /**
  3334. * 审批
  3335. * @param ctx
  3336. * @return {Promise<void>}
  3337. */
  3338. async checkApplyAudit(ctx) {
  3339. try {
  3340. const auditConst = audit.changeApply;
  3341. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  3342. throw '当前变更申请数据有误';
  3343. }
  3344. if (ctx.change.curAuditorIds.length === 0 || ctx.change.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  3345. throw '您无权进行该操作';
  3346. }
  3347. const data = {
  3348. checkType: parseInt(ctx.request.body.checkType),
  3349. opinion: ctx.request.body.opinion,
  3350. };
  3351. if (!data.checkType || isNaN(data.checkType)) {
  3352. throw '提交数据错误';
  3353. }
  3354. if (ctx.request.body.notice_uid) {
  3355. data.notice_code = ctx.request.body.notice_code;
  3356. data.notice_uid = ctx.request.body.notice_uid;
  3357. }
  3358. // if (data.checkType === auditConst.status.checkNo) {
  3359. // if (!data.checkType || isNaN(data.checkType)) {
  3360. // throw '提交数据错误';
  3361. // }
  3362. // }
  3363. await ctx.service.changeApplyAudit.check(ctx.change.id, data, ctx.change.times);
  3364. ctx.redirect(ctx.request.header.referer);
  3365. } catch (err) {
  3366. this.log(err);
  3367. ctx.session.postError = err.toString();
  3368. ctx.redirect(ctx.request.header.referer);
  3369. }
  3370. }
  3371. /**
  3372. * 变更清单 - 操作 (Ajax)
  3373. * @param ctx
  3374. * @return {Promise<void>}
  3375. */
  3376. async saveApplyListsData(ctx) {
  3377. try {
  3378. const data = JSON.parse(ctx.request.body.data);
  3379. const responseData = {
  3380. err: 0,
  3381. msg: '',
  3382. data: {},
  3383. };
  3384. switch (data.type) {
  3385. case 'add':
  3386. responseData.data = await ctx.service.changeApplyList.add(data.updateData);
  3387. break;
  3388. case 'batchadd':
  3389. responseData.data = await ctx.service.changeApplyList.batchAdd(data);
  3390. break;
  3391. case 'del':
  3392. await ctx.service.changeApplyList.del(data.ids);
  3393. // 取所有工料表
  3394. responseData.data = await ctx.service.changeApplyList.getList(ctx.change.id);
  3395. break;
  3396. case 'update':
  3397. // if (data.updateData.code === '' || data.updateData.code === null) {
  3398. // throw '请先输入编号';
  3399. // }
  3400. await ctx.service.changeApplyList.save(data.updateData);
  3401. break;
  3402. case 'paste':
  3403. await ctx.service.changeApplyList.saveDatas(data.updateData);
  3404. // 取所有工料表
  3405. responseData.data = await ctx.service.changeApplyList.getList(ctx.change.id);
  3406. break;
  3407. case 'paste_amount_rows':
  3408. await ctx.service.changeApplyList.saveDatas(data.updateData);
  3409. responseData.data = await ctx.service.changeApplyList.getList(ctx.change.id);
  3410. break;
  3411. case 'list_rule':
  3412. const result = await ctx.service.tender.saveTenderData(ctx.tender.id, { c_apply_list_rule: data.postData });
  3413. if (!result) {
  3414. throw '修改失败';
  3415. }
  3416. break;
  3417. // case 'update_tp':
  3418. // await ctx.service.changeApply.saveInfo(ctx.change.id, { name: 'total_price', val: data.updateData });
  3419. // break;
  3420. default: throw '参数有误';
  3421. }
  3422. ctx.body = responseData;
  3423. } catch (err) {
  3424. this.log(err);
  3425. ctx.body = { err: 1, msg: err.toString(), data: null };
  3426. }
  3427. }
  3428. /**
  3429. * 变更申请重新审批
  3430. * @param {Object} ctx - egg全局变量
  3431. * @return {void}
  3432. */
  3433. async checkApplyAgain(ctx) {
  3434. try {
  3435. // 获取终审
  3436. // const auditInfo = await this.ctx.service.changeApplyAudit.getAuditorByStatus(ctx.change.id, audit.changeApply.status.checked);
  3437. if (ctx.change.status !== audit.changeApply.status.checked) {
  3438. throw '您无权进行该操作';
  3439. }
  3440. // 判断是否被变更申请调用了,是则无法发起修订
  3441. const projectInfo = await ctx.service.changePlan.getDataByCondition({ tid: ctx.tender.id, apply_code: ctx.change.code });
  3442. if (projectInfo) {
  3443. throw '该变更申请已被变更方案调用,无法发起重新审批';
  3444. }
  3445. if (ctx.session.sessionUser.loginStatus === 0) {
  3446. const code = ctx.request.body.code;
  3447. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3448. if (!pa.auth_mobile) {
  3449. throw '未绑定手机号';
  3450. }
  3451. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  3452. const cacheCode = await app.redis.get(cacheKey);
  3453. // console.log(cacheCode);
  3454. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  3455. throw '验证码不正确!';
  3456. }
  3457. }
  3458. if ((ctx.change.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0) && ctx.change.status === audit.changeApply.status.checked) {
  3459. // 重新审批
  3460. const result = await ctx.service.changeApplyAudit.checkAgain(ctx.change);
  3461. if (!result) {
  3462. throw '重新审批失败';
  3463. }
  3464. } else {
  3465. throw '您无权进行该操作';
  3466. }
  3467. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  3468. ctx.body = {
  3469. err: 0,
  3470. url: ctx.request.header.referer,
  3471. msg: '',
  3472. };
  3473. } catch (err) {
  3474. console.log(err);
  3475. // ctx.redirect(ctx.request.header.referer);
  3476. ctx.body = {
  3477. err: 1,
  3478. // url: ctx.request.header.referer,
  3479. msg: err,
  3480. };
  3481. }
  3482. }
  3483. /**
  3484. * 变更申请修订重新上报
  3485. * @param {Object} ctx - egg全局变量
  3486. * @return {void}
  3487. */
  3488. async checkApplyRevise(ctx) {
  3489. try {
  3490. if (ctx.change.status !== audit.changeApply.status.checked || ctx.session.sessionUser.accountId !== ctx.change.uid) {
  3491. throw '您无权进行该操作';
  3492. }
  3493. // 判断是否被变更申请调用了,是则无法发起修订
  3494. const projectInfo = await ctx.service.changePlan.getDataByCondition({ tid: ctx.tender.id, apply_code: ctx.change.code });
  3495. if (projectInfo) {
  3496. throw '该变更申请已被变更方案调用,无法发起修订';
  3497. }
  3498. if (ctx.session.sessionUser.loginStatus === 0) {
  3499. const code = ctx.request.body.code;
  3500. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3501. if (!pa.auth_mobile) {
  3502. throw '未绑定手机号';
  3503. }
  3504. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  3505. const cacheCode = await app.redis.get(cacheKey);
  3506. // console.log(cacheCode);
  3507. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  3508. throw '验证码不正确!';
  3509. }
  3510. }
  3511. // 重新审批
  3512. const result = await ctx.service.changeApplyAudit.checkRevise(ctx.change);
  3513. if (!result) {
  3514. throw '修订发起失败';
  3515. }
  3516. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  3517. ctx.body = {
  3518. err: 0,
  3519. url: ctx.request.header.referer,
  3520. msg: '',
  3521. };
  3522. } catch (err) {
  3523. console.log(err);
  3524. // ctx.redirect(ctx.request.header.referer);
  3525. ctx.body = {
  3526. err: 1,
  3527. // url: ctx.request.header.referer,
  3528. msg: err,
  3529. };
  3530. }
  3531. }
  3532. /**
  3533. * 变更令撤销修订
  3534. * @param {Object} ctx - egg全局变量
  3535. * @return {void}
  3536. */
  3537. async cancelApplyRevise(ctx) {
  3538. try {
  3539. if (!(ctx.change.status === audit.changeApply.status.revise && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.session.sessionUser.accountId === ctx.session.sessionUser.is_admin))) {
  3540. throw '您无权进行该操作';
  3541. }
  3542. // 重新审批
  3543. const result = await ctx.service.changeApplyAudit.cancelRevise(ctx.change);
  3544. if (!result) {
  3545. throw '撤销修订失败';
  3546. }
  3547. ctx.body = {
  3548. err: 0,
  3549. url: ctx.request.header.referer,
  3550. msg: '',
  3551. };
  3552. } catch (err) {
  3553. console.log(err);
  3554. ctx.body = {
  3555. err: 1,
  3556. msg: err,
  3557. };
  3558. }
  3559. }
  3560. // 变更方案
  3561. async _filterChangesPlan(ctx, status = 0) {
  3562. const tenderId = ctx.params.id;
  3563. ctx.session.sessionUser.tenderId = tenderId;
  3564. const tender = await this.service.tender.getDataById(ctx.tender.id);
  3565. // const tender = ctx.tender;
  3566. // const tenderList = await this.service.tender.getList();
  3567. const page = ctx.page;
  3568. const pageSize = ctx.pageSize;
  3569. const sorts = ctx.query.sort ? ctx.query.sort : 0;
  3570. const orders = ctx.query.order ? ctx.query.order : 0;
  3571. const changes = await ctx.service.changePlan.getListByStatus(tender.id, status, 1, sorts, orders);
  3572. const total = await ctx.service.changePlan.getCountByStatus(tender.id, status);
  3573. let page_total = 0;
  3574. const tp = await ctx.service.changePlan.getTp(tender.id, status);
  3575. for (const c of changes) {
  3576. if (c.status !== audit.change.status.checked || !c.final_auditor_str) {
  3577. c.curAuditors = await ctx.service.changePlanAudit.getAuditorsByStatus(c.id, c.status, c.times);
  3578. // if (c.status === audit.changePlan.status.checkNoPre) {
  3579. // c.curAuditors2 = await ctx.service.changePlanAudit.getAuditorsByStatus(c.id, audit.changePlan.status.checking, c.times);
  3580. // }
  3581. if (c.status === audit.change.status.checked && c.curAuditors.length > 0) {
  3582. const final_auditor_str = c.curAuditors[0].audit_type === auditType.key.common
  3583. ? c.curAuditors[0].name + (c.curAuditors[0].role ? '-' + c.curAuditors[0].role : '')
  3584. : ctx.helper.transFormToChinese(c.curAuditors[0].audit_order) + '审';
  3585. await ctx.service.changePlan.defaultUpdate({ final_auditor_str }, { where: { id: c.id } });
  3586. }
  3587. }
  3588. page_total = ctx.helper.add(page_total, c.total_price);
  3589. }
  3590. const tender_userInfo = await ctx.service.projectAccount.getDataById(ctx.tender.data.user_id);
  3591. // 分页相关
  3592. const pageInfo = {
  3593. page,
  3594. pageSizeSelect: 1,
  3595. pageSize,
  3596. total_num: total,
  3597. total: Math.ceil(total / pageSize),
  3598. queryData: JSON.stringify(ctx.urlInfo.query),
  3599. };
  3600. const filter = JSON.parse(JSON.stringify(audit.changePlan.filter));
  3601. filter.count = [];
  3602. filter.count[filter.status.pending] = await ctx.service.changePlan.getCountByStatus(tender.id, filter.status.pending);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  3603. filter.count[filter.status.uncheck] = await ctx.service.changePlan.getCountByStatus(tender.id, filter.status.uncheck);// await ctx.service.change.checkingDatas(tender.id, ctx.session.sessionUser.accountId);
  3604. filter.count[filter.status.checking] = await ctx.service.changePlan.getCountByStatus(tender.id, filter.status.checking);// await ctx.service.change.checkedDatas(tender.id, ctx.session.sessionUser.accountId);
  3605. filter.count[filter.status.checked] = await ctx.service.changePlan.getCountByStatus(tender.id, filter.status.checked);// await ctx.service.change.pendingDatas(tender.id, ctx.session.sessionUser.accountId);
  3606. // 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);
  3607. let codeRule = [];
  3608. let c_connector = '1';
  3609. let c_rule_first = 1;
  3610. const rule_type = 'plan';
  3611. if (tender.c_code_rules) {
  3612. const c_code_rules = JSON.parse(tender.c_code_rules);
  3613. codeRule = c_code_rules[rule_type + '_rule'] !== undefined ? c_code_rules[rule_type + '_rule'] : [];
  3614. c_connector = c_code_rules[rule_type + '_connector'] !== undefined ? c_code_rules[rule_type + '_connector'] : '1';
  3615. c_rule_first = c_code_rules[rule_type + '_rule_first'] !== undefined ? c_code_rules[rule_type + '_rule_first'] : 1;
  3616. }
  3617. for (const rule of codeRule) {
  3618. switch (rule.rule_type) {
  3619. case codeRuleConst.measure.ruleType.dealCode:
  3620. rule.preview = ctx.tender.info.deal_info.dealCode;
  3621. break;
  3622. case codeRuleConst.measure.ruleType.tenderName:
  3623. rule.preview = tender.name;
  3624. break;
  3625. case codeRuleConst.measure.ruleType.inDate:
  3626. rule.preview = moment().format('YYYY');
  3627. break;
  3628. case codeRuleConst.measure.ruleType.text:
  3629. rule.preview = rule.text;
  3630. break;
  3631. case codeRuleConst.measure.ruleType.addNo:
  3632. const s = '0000000000';
  3633. rule.preview = s.substr(s.length - rule.format);
  3634. break;
  3635. default: break;
  3636. }
  3637. }
  3638. const changeApplyList = await ctx.service.changeApply.getAllDataByCondition({ where: { tid: tender.id, status: audit.changeApply.status.checked } });
  3639. const allApplyCodes = await ctx.service.changePlan.getAllDataByCondition({
  3640. columns: ['apply_code'],
  3641. where: {
  3642. tid: tender.id,
  3643. },
  3644. });
  3645. const acLists = allApplyCodes.length > 0 ? ctx.app._.uniq(ctx.app._.map(allApplyCodes, 'apply_code')) : [];
  3646. const renderData = {
  3647. uid: ctx.session.sessionUser.accountId,
  3648. tender,
  3649. pageInfo,
  3650. changes,
  3651. status,
  3652. rule_type,
  3653. codeRule,
  3654. c_connector,
  3655. c_rule_first,
  3656. filter,
  3657. plan_username: tender_userInfo ? tender_userInfo.name : null,
  3658. ruleType: codeRuleConst.ruleType[rule_type],
  3659. dealCode: ctx.tender.info.deal_info.dealCode,
  3660. auditConst: audit.changePlan,
  3661. ruleConst: codeRuleConst.measure,
  3662. changeConst,
  3663. auditType,
  3664. changeApplyList,
  3665. acLists,
  3666. page_total,
  3667. tp,
  3668. tenderMenu: this.menu.tenderMenu,
  3669. preUrl: '/tender/' + tender.id,
  3670. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.plan),
  3671. };
  3672. await this.layout('change/plan.ejs', renderData, 'change/plan_modal.ejs');
  3673. }
  3674. /**
  3675. * 变更申请列表 页面 (Get)
  3676. *
  3677. * @param {Object} ctx - egg全局变量
  3678. * @return {void}
  3679. */
  3680. async plan(ctx) {
  3681. try {
  3682. await this._filterChangesPlan(ctx);
  3683. } catch (err) {
  3684. this.log(err);
  3685. ctx.redirect('/dashboard');
  3686. }
  3687. }
  3688. /**
  3689. * 变更管理 状态筛选 页面 (Get)
  3690. * @param {Object} ctx - egg全局变量
  3691. * @return {void}
  3692. */
  3693. async planStatus(ctx) {
  3694. try {
  3695. const status = parseInt(ctx.params.status);
  3696. await this._filterChangesPlan(ctx, status);
  3697. } catch (err) {
  3698. this.logger.error(err);
  3699. ctx.redirect('/tender/' + ctx.params.id + '/change/plan');
  3700. }
  3701. }
  3702. /**
  3703. * 审批流程(Get)
  3704. * @param ctx
  3705. * @return {Promise<void>}
  3706. */
  3707. async changePlanAuditors(ctx) {
  3708. try {
  3709. const id = JSON.parse(ctx.request.body.data).id;
  3710. const tenderId = ctx.params.id;
  3711. const changeInfo = await ctx.service.changePlan.getDataById(id);
  3712. await ctx.service.changePlan.loadChangeUser(changeInfo);
  3713. await ctx.service.changePlan.loadChangeAuditViewData(changeInfo);
  3714. ctx.body = { err: 0, msg: '', data: changeInfo };
  3715. } catch (error) {
  3716. this.log(error);
  3717. ctx.body = { err: 1, msg: error.toString(), data: null };
  3718. }
  3719. }
  3720. /**
  3721. * 新增变更方案 (Post)
  3722. *
  3723. * @param {Object} ctx - egg全局变量
  3724. * @return {void}
  3725. */
  3726. async planAdd(ctx) {
  3727. try {
  3728. const tenderId = ctx.params.id;
  3729. if (!tenderId) {
  3730. throw '当前未打开标段';
  3731. }
  3732. const data = JSON.parse(ctx.request.body.data);
  3733. if (!data.code || data.code === '') {
  3734. throw '变更方案编号不能为空';
  3735. }
  3736. // 在生成新变更方案后,需要copy前一个变更方案报表的签名信息
  3737. const lastChange = await ctx.service.changePlan.getLastChange(tenderId);
  3738. const change = await ctx.service.changePlan.add(tenderId, ctx.session.sessionUser.accountId, data.code, data.apply_code, data.name);
  3739. await ctx.service.roleRptRel.createRoleRelationshipFromOtherBz(tenderId, '-301', change.id, lastChange ? lastChange.id : null);
  3740. ctx.body = { err: 0, msg: '', data: change };
  3741. } catch (err) {
  3742. this.log(err);
  3743. ctx.body = { err: 1, msg: err.toString() };
  3744. }
  3745. }
  3746. /**
  3747. * 删除变更立项
  3748. * @param {Object} ctx - egg全局变量
  3749. * @return {void}
  3750. */
  3751. async planDelete(ctx) {
  3752. try {
  3753. const result = await ctx.service.changePlan.delete(ctx.request.body.cpid);
  3754. if (!result) {
  3755. throw '删除变更方案失败';
  3756. }
  3757. ctx.redirect(ctx.request.header.referer);
  3758. } catch (err) {
  3759. console.log(err);
  3760. ctx.redirect(ctx.request.header.referer);
  3761. }
  3762. }
  3763. /**
  3764. * 获取审批界面所需的 原报、审批人数据等
  3765. * @param ctx
  3766. * @return {Promise<void>}
  3767. * @private
  3768. */
  3769. async _getChangePlanAuditViewData(ctx) {
  3770. await ctx.service.changePlan.loadChangeAuditViewData(ctx.change);
  3771. }
  3772. async planInformation(ctx) {
  3773. try {
  3774. const whiteList = this.ctx.app.config.multipart.whitelist;
  3775. const tender = await ctx.service.tender.getDataById(ctx.tender.id);
  3776. await this._getChangePlanAuditViewData(ctx);
  3777. // 获取附件列表
  3778. const fileList = await ctx.service.changePlanAtt.getAllChangePlanAtt(ctx.tender.id, ctx.change.id);
  3779. // 获取清单列表
  3780. const changeList = await ctx.service.changePlanList.getList(ctx.change.id);
  3781. if (ctx.change.status === audit.changePlan.status.checking || ctx.change.status === audit.changePlan.status.checked) {
  3782. // const listAudits = await ctx.service.changePlanAudit.getAuditGroupByList(ctx.change.id, ctx.change.times);
  3783. // ctx.change.listAudits = listAudits;
  3784. for (const cl of changeList) {
  3785. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  3786. // 清单表页赋值
  3787. for (const au in ctx.change.userGroups) {
  3788. if (ctx.change.userGroups[au][0].audit_order !== 0) {
  3789. cl['audit_amount_' + ctx.change.userGroups[au][0].audit_order] =
  3790. (ctx.change.userGroups[au][0].audit_type === auditType.key.and &&
  3791. ctx.helper._.findIndex(ctx.change.userGroups[au], { aid: ctx.session.sessionUser.accountId, status: audit.changePlan.status.checked }) !== -1) ||
  3792. (ctx.change.shenpiPower && ctx.helper._.findIndex(ctx.change.userGroups[au], { aid: ctx.session.sessionUser.accountId }) !== -1) ?
  3793. cl.spamount : (audit_amount[au - 1] !== undefined ? parseFloat(audit_amount[au - 1]) : null);
  3794. }
  3795. }
  3796. }
  3797. }
  3798. // 获取用户人验证手机号
  3799. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  3800. const auth_mobile = pa.auth_mobile;
  3801. const userPermission = pa && pa.permission ? JSON.parse(pa.permission) : null;
  3802. const deleteFilePermission = !!(userPermission && userPermission.change !== undefined && userPermission.change.indexOf('2') !== -1);
  3803. const changeClass = await this._getOrUpdateClass(ctx, 'changePlan');
  3804. const renderData = {
  3805. tender,
  3806. change: ctx.change,
  3807. listRule: tender.c_plan_list_rule ? JSON.parse(tender.c_plan_list_rule) : { source: 1, rule: ['unit', 'unit_price'] },
  3808. changeList,
  3809. changeClass,
  3810. changeConst,
  3811. auditConst: audit.changePlan,
  3812. fileList,
  3813. whiteList,
  3814. authMobile: auth_mobile,
  3815. deleteFilePermission,
  3816. auditType,
  3817. shenpiConst,
  3818. tpUnit: ctx.change.decimal ? ctx.change.decimal.tp : ctx.tender.info.decimal.tp,
  3819. upUnit: ctx.change.decimal ? ctx.change.decimal.up : ctx.tender.info.decimal.up,
  3820. changeUnits: changeConst.units,
  3821. precision: ctx.change.decimal && ctx.change.decimal.precision ? ctx.change.decimal.precision : ctx.tender.info.precision,
  3822. returnUrl: this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/plan') && !this.app._.includes(ctx.request.headers.referer, '/tender/' + ctx.tender.id + '/change/plan/' + ctx.change.id + '/information') ? ctx.request.headers.referer : null,
  3823. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.change.plan_information),
  3824. preUrl: '/tender/' + ctx.tender.id + '/change/plan/' + ctx.change.id + '/information',
  3825. };
  3826. // if ((ctx.change.status === audit.changePlan.status.uncheck || ctx.change.status === audit.changePlan.status.checkNo || ctx.change.status === audit.changePlan.status.revise) && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.tender.isTourist)) {
  3827. // data.accountGroup = accountGroup;
  3828. // 获取所有项目参与者
  3829. const accountList = await ctx.service.projectAccount.getAllSubProjectAccount(ctx.subProject);
  3830. renderData.accountList = accountList;
  3831. const unitList = await ctx.service.constructionUnit.getAllDataByCondition({ where: { pid: ctx.session.sessionProject.id } });
  3832. renderData.accountGroup = unitList.map(item => {
  3833. const groupList = accountList.filter(item1 => item1.company === item.name);
  3834. return { groupName: item.name, groupList };
  3835. }).filter(x => { return x.groupList.length > 0; });
  3836. // 获取固定审批流列表
  3837. if (ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  3838. renderData.spGroupList = await ctx.service.shenpiGroup.getGroupListByChangeType(ctx.tender.id, shenpiConst.sp_type.change, 'changePlan');
  3839. }
  3840. // }
  3841. await this.layout('change/plan_information.ejs', renderData, 'change/plan_information_modal.ejs');
  3842. } catch (err) {
  3843. this.log(err);
  3844. ctx.redirect('/tender/' + ctx.params.id + '/change/plan');
  3845. }
  3846. }
  3847. async changePlanSpGroup(ctx) {
  3848. try {
  3849. const data = JSON.parse(ctx.request.body.data);
  3850. const result = await ctx.service.changePlanAudit.changeSpGroup(ctx.change, data.sp_group);
  3851. if (!result) {
  3852. throw '切换审批组失败';
  3853. }
  3854. const auditors = await ctx.service.changePlanAudit.getUserGroup(ctx.change.id, ctx.change.times);
  3855. ctx.body = { err: 0, msg: '', data: auditors };
  3856. } catch (err) {
  3857. ctx.body = { err: 1, msg: err.toString(), data: null };
  3858. }
  3859. }
  3860. // 审批相关
  3861. /**
  3862. * 添加审批人
  3863. * @param ctx
  3864. * @return {Promise<void>}
  3865. */
  3866. async addPlanAudit(ctx) {
  3867. try {
  3868. const auditConst = audit.changePlan;
  3869. const data = JSON.parse(ctx.request.body.data);
  3870. const id = this.app._.toInteger(data.auditorId);
  3871. if (isNaN(id) || id <= 0) {
  3872. throw '参数错误';
  3873. }
  3874. // 检查权限等
  3875. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  3876. throw '您无权添加审核人';
  3877. }
  3878. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  3879. throw '当前不允许添加审核人';
  3880. }
  3881. ctx.change.auditorList = await ctx.service.changePlanAudit.getAuditors(ctx.change.id, ctx.change.times);
  3882. // 检查审核人是否已存在
  3883. const exist = this.app._.find(ctx.change.auditorList, { aid: id });
  3884. if (exist) {
  3885. throw '该审核人已存在,请勿重复添加';
  3886. }
  3887. // const shenpiInfo = await ctx.service.shenpiAudit.getDataByCondition({ tid: ctx.tender.id, sp_type: shenpiConst.sp_type.material, sp_status: shenpiConst.sp_status.gdzs });
  3888. // const is_gdzs = shenpiInfo && ctx.tender.info.shenpi.material === shenpiConst.sp_status.gdzs ? 1 : 0;
  3889. const result = await ctx.service.changePlanAudit.addAuditor(ctx.change.id, id, ctx.change.times);
  3890. if (!result) {
  3891. throw '添加审核人失败';
  3892. }
  3893. const auditors = await ctx.service.changePlanAudit.getUserGroup(ctx.change.id, ctx.change.times);
  3894. ctx.body = { err: 0, msg: '', data: auditors };
  3895. } catch (err) {
  3896. this.log(err);
  3897. ctx.body = { err: 1, msg: err.toString(), data: null };
  3898. }
  3899. }
  3900. /**
  3901. * 移除审批人
  3902. * @param ctx
  3903. * @return {Promise<void>}
  3904. */
  3905. async deletePlanAudit(ctx) {
  3906. try {
  3907. const data = JSON.parse(ctx.request.body.data);
  3908. const id = data.auditorId instanceof Number ? data.auditorId : this.app._.toNumber(data.auditorId);
  3909. if (isNaN(id) || id <= 0) {
  3910. throw '参数错误';
  3911. }
  3912. const result = await ctx.service.changePlanAudit.deleteAuditor(ctx.change.id, id, ctx.change.times);
  3913. if (!result) {
  3914. throw '移除审核人失败';
  3915. }
  3916. const auditors = await ctx.service.changePlanAudit.getAuditors(ctx.change.id, ctx.change.times);
  3917. ctx.body = { err: 0, msg: '', data: auditors };
  3918. } catch (err) {
  3919. ctx.body = { err: 1, msg: err.toString(), data: null };
  3920. }
  3921. }
  3922. async savePlanAudit(ctx) {
  3923. try {
  3924. // if (ctx.change.revising) {
  3925. // throw '台账修订中,请勿修改提交期数据';
  3926. // }
  3927. const data = JSON.parse(ctx.request.body.data);
  3928. if (ctx.session.sessionUser.is_admin && ctx.change.status !== audit.change.status.checked) {
  3929. await ctx.service.changePlanAudit.saveAudit(ctx.change.id, ctx.change.times, ctx.change.sp_group, data);
  3930. const auditors = await ctx.service.changePlanAudit.getUniqUserGroup(ctx.change.id, ctx.change.times);
  3931. ctx.body = { err: 0, msg: '', data: auditors };
  3932. } else {
  3933. throw '您无权进行该操作';
  3934. }
  3935. } catch (err) {
  3936. this.log(err);
  3937. // ctx.session.postError = err.toString();
  3938. // ctx.redirect(ctx.request.header.referer);
  3939. ctx.body = {
  3940. err: 1,
  3941. // url: ctx.request.header.referer,
  3942. msg: err,
  3943. };
  3944. }
  3945. }
  3946. /**
  3947. * 上传附件
  3948. * @param {*} ctx 上下文
  3949. */
  3950. async uploadPlanFile(ctx) {
  3951. let stream;
  3952. try {
  3953. const auditConst = audit.changePlan;
  3954. // this._checkAdvanceFileCanModify(ctx);
  3955. const parts = this.ctx.multipart({
  3956. autoFields: true,
  3957. });
  3958. const files = [];
  3959. const create_time = Date.parse(new Date()) / 1000;
  3960. let idx = 0;
  3961. const extra_upload = ctx.change.status === auditConst.status.checked;
  3962. while ((stream = await parts()) !== undefined) {
  3963. if (!stream.filename) {
  3964. // 如果没有传入直接返回
  3965. return;
  3966. }
  3967. const fileInfo = path.parse(stream.filename);
  3968. const filepath = `app/public/upload/${this.ctx.tender.id.toString()}/change_plan/fujian_${create_time + idx.toString() + fileInfo.ext}`;
  3969. // await ctx.helper.saveStreamFile(stream, path.resolve(this.app.baseDir, 'app', filepath));
  3970. await ctx.app.fujianOss.put(ctx.app.config.fujianOssFolder + filepath, stream);
  3971. files.push({ filepath, name: stream.filename, ext: fileInfo.ext });
  3972. ++idx;
  3973. stream && (await sendToWormhole(stream));
  3974. }
  3975. const in_time = new Date();
  3976. const payload = files.map(file => {
  3977. let idx;
  3978. if (Array.isArray(parts.field.name)) {
  3979. idx = parts.field.name.findIndex(name => name === file.name);
  3980. } else {
  3981. idx = 'isString';
  3982. }
  3983. const newFile = {
  3984. tid: ctx.tender.id,
  3985. cpid: ctx.change.id,
  3986. uid: ctx.session.sessionUser.accountId,
  3987. filename: file.name,
  3988. fileext: file.ext,
  3989. filesize: ctx.helper.bytesToSize(idx === 'isString' ? parts.field.size : parts.field.size[idx]),
  3990. filepath: file.filepath,
  3991. upload_time: in_time,
  3992. extra_upload,
  3993. };
  3994. return newFile;
  3995. });
  3996. // 执行文件信息写入数据库
  3997. await ctx.service.changePlanAtt.saveFileMsgToDb(payload);
  3998. // 将最新的当前标段的所有文件信息返回
  3999. const data = await ctx.service.changePlanAtt.getAllChangePlanAtt(ctx.tender.id, ctx.change.id);
  4000. ctx.body = { err: 0, msg: '', data };
  4001. } catch (err) {
  4002. stream && (await sendToWormhole(stream));
  4003. this.log(err);
  4004. ctx.body = { err: 1, msg: err.toString(), data: null };
  4005. }
  4006. }
  4007. /**
  4008. * 删除附件
  4009. * @param {Ojbect} ctx 上下文
  4010. */
  4011. async deletePlanFile(ctx) {
  4012. try {
  4013. const { id } = JSON.parse(ctx.request.body.data);
  4014. const fileInfo = await ctx.service.changePlanAtt.getDataById(id);
  4015. if (fileInfo || Object.keys(fileInfo).length) {
  4016. // 先删除文件
  4017. // await fs.unlinkSync(path.resolve(this.app.baseDir, './app', fileInfo.filepath));
  4018. await ctx.app.fujianOss.delete(ctx.app.config.fujianOssFolder + fileInfo.filepath);
  4019. // 再删除数据库
  4020. await ctx.service.changePlanAtt.delete(id);
  4021. } else {
  4022. throw '不存在该文件';
  4023. }
  4024. const data = await ctx.service.changePlanAtt.getAllChangePlanAtt(ctx.tender.id, ctx.change.id);
  4025. ctx.body = { err: 0, msg: '请求成功', data };
  4026. } catch (err) {
  4027. this.log(err);
  4028. ctx.body = { err: 1, msg: err.toString(), data: null };
  4029. }
  4030. }
  4031. /**
  4032. * 下载附件
  4033. * @param {Object} ctx - egg全局变量
  4034. * @return {void}
  4035. */
  4036. async downloadPlanFile(ctx) {
  4037. const id = ctx.params.fid;
  4038. if (id) {
  4039. try {
  4040. const fileInfo = await ctx.service.changePlanAtt.getDataById(id);
  4041. if (fileInfo !== undefined && fileInfo !== '') {
  4042. // const fileName = path.join(__dirname, '../', fileInfo.filepath);
  4043. // 解决中文无法下载问题
  4044. const userAgent = (ctx.request.header['user-agent'] || '').toLowerCase();
  4045. let disposition = '';
  4046. if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
  4047. disposition = 'attachment; filename=' + encodeURIComponent(fileInfo.filename);
  4048. } else if (userAgent.indexOf('firefox') >= 0) {
  4049. disposition = 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileInfo.filename) + '"';
  4050. } else {
  4051. /* safari等其他非主流浏览器只能自求多福了 */
  4052. disposition = 'attachment; filename=' + new Buffer(fileInfo.filename).toString('binary');
  4053. }
  4054. ctx.response.set({
  4055. 'Content-Type': 'application/octet-stream',
  4056. 'Content-Disposition': disposition,
  4057. 'Content-Length': fileInfo.filesize,
  4058. });
  4059. // ctx.body = await fs.createReadStream(fileName);
  4060. ctx.body = await ctx.helper.ossFileGet(fileInfo.filepath);
  4061. } else {
  4062. throw '不存在该文件';
  4063. }
  4064. } catch (err) {
  4065. this.log(err);
  4066. this.setMessage(err.toString(), this.messageType.ERROR);
  4067. }
  4068. }
  4069. }
  4070. async planInformationSave(ctx) {
  4071. try {
  4072. const data = JSON.parse(ctx.request.body.data);
  4073. if (data.name === 'code') {
  4074. const info = await ctx.service.changePlan.isRepeat(ctx.change.id, data.val, ctx.tender.id);
  4075. if (info) {
  4076. throw '该编号已存在';
  4077. }
  4078. }
  4079. const result = await ctx.service.changePlan.saveInfo(ctx.change.id, data);
  4080. if (!result) {
  4081. throw '修改失败';
  4082. }
  4083. ctx.body = { err: 0, msg: '请求成功', data: null };
  4084. } catch (err) {
  4085. this.log(err);
  4086. ctx.body = { err: 1, msg: err.toString(), data: null };
  4087. }
  4088. }
  4089. /**
  4090. * 上报和重新上报
  4091. * @param ctx
  4092. * @return {Promise<void>}
  4093. */
  4094. async startPlanAudit(ctx) {
  4095. try {
  4096. const auditConst = audit.changePlan;
  4097. // 检查权限等
  4098. if (!ctx.change) {
  4099. throw '数据错误';
  4100. }
  4101. if (ctx.change.uid !== ctx.session.sessionUser.accountId) {
  4102. throw '您无权上报该变更方案数据';
  4103. }
  4104. if (ctx.change.status === auditConst.status.checking || ctx.change.status === auditConst.status.checked) {
  4105. throw '该变更方案数据当前无法上报';
  4106. }
  4107. await ctx.service.changePlanAudit.start(ctx.change.id, ctx.change.times);
  4108. ctx.redirect(ctx.request.header.referer);
  4109. } catch (err) {
  4110. this.log(err);
  4111. ctx.session.postError = err.toString();
  4112. ctx.redirect(ctx.request.header.referer);
  4113. }
  4114. }
  4115. /**
  4116. * 审批
  4117. * @param ctx
  4118. * @return {Promise<void>}
  4119. */
  4120. async checkPlanAudit(ctx) {
  4121. try {
  4122. const auditConst = audit.changePlan;
  4123. if (!ctx.change || ctx.change.status !== auditConst.status.checking) {
  4124. throw '当前变更方案数据有误';
  4125. }
  4126. if (ctx.change.curAuditorIds.length === 0 || ctx.change.curAuditorIds.indexOf(ctx.session.sessionUser.accountId) === -1) {
  4127. throw '您无权进行该操作';
  4128. }
  4129. const data = {
  4130. checkType: parseInt(ctx.request.body.checkType),
  4131. opinion: ctx.request.body.opinion,
  4132. };
  4133. if (!data.checkType || isNaN(data.checkType)) {
  4134. throw '提交数据错误';
  4135. }
  4136. // if (data.checkType === auditConst.status.checkNo) {
  4137. // if (!data.checkType || isNaN(data.checkType)) {
  4138. // throw '提交数据错误';
  4139. // }
  4140. // }
  4141. await ctx.service.changePlanAudit.check(ctx.change.id, data, ctx.change.times);
  4142. ctx.redirect(ctx.request.header.referer);
  4143. } catch (err) {
  4144. this.log(err);
  4145. console.log(err);
  4146. ctx.session.postError = err.toString();
  4147. ctx.redirect(ctx.request.header.referer);
  4148. }
  4149. }
  4150. /**
  4151. * 变更清单 - 操作 (Ajax)
  4152. * @param ctx
  4153. * @return {Promise<void>}
  4154. */
  4155. async savePlanListsData(ctx) {
  4156. try {
  4157. const data = JSON.parse(ctx.request.body.data);
  4158. const responseData = {
  4159. err: 0,
  4160. msg: '',
  4161. data: {},
  4162. };
  4163. switch (data.type) {
  4164. case 'add':
  4165. responseData.data = await ctx.service.changePlanList.add(data.updateData);
  4166. break;
  4167. case 'batchadd':
  4168. responseData.data = await ctx.service.changePlanList.batchAdd(data);
  4169. break;
  4170. case 'del':
  4171. await ctx.service.changePlanList.del(data.ids);
  4172. // 取所有工料表
  4173. responseData.data = await ctx.service.changePlanList.getList(ctx.change.id);
  4174. break;
  4175. case 'update':
  4176. // if (data.updateData.code === '' || data.updateData.code === null) {
  4177. // throw '请先输入编号';
  4178. // }
  4179. await ctx.service.changePlanList.save(data.updateData);
  4180. break;
  4181. case 'paste':
  4182. await ctx.service.changePlanList.saveDatas(data.updateData);
  4183. // 取所有工料表
  4184. responseData.data = await ctx.service.changePlanList.getList(ctx.change.id);
  4185. if (ctx.change.status === audit.changePlan.status.checking || ctx.change.status === audit.changePlan.status.checked) {
  4186. const listAudits = await ctx.service.changePlanAudit.getAuditGroupByList(ctx.change.id, ctx.change.times);
  4187. for (const cl of responseData.data) {
  4188. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  4189. // 清单表页赋值
  4190. for (const [index, au] of listAudits.entries()) {
  4191. cl['audit_amount_' + au.aid] = ctx.change.shenpiPower && au.aid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index] ? parseFloat(audit_amount[index]) : null);
  4192. }
  4193. }
  4194. }
  4195. break;
  4196. case 'list_rule':
  4197. const result = await ctx.service.tender.saveTenderData(ctx.tender.id, { c_plan_list_rule: data.postData });
  4198. if (!result) {
  4199. throw '修改失败';
  4200. }
  4201. break;
  4202. case 'paste_amount_rows':
  4203. await ctx.service.changePlanList.saveDatas(data.updateData);
  4204. const changeList = await ctx.service.changePlanList.getList(ctx.change.id);
  4205. const listAudits = await ctx.service.changePlanAudit.getAuditGroupByList(ctx.change.id, ctx.change.times);
  4206. for (const cl of changeList) {
  4207. // 清单表页赋值
  4208. const audit_amount = cl.audit_amount !== null && cl.audit_amount !== '' ? cl.audit_amount.split(',') : '';
  4209. // 清单表页赋值
  4210. for (const [index, au] of listAudits.entries()) {
  4211. cl['audit_amount_' + au.aid] = ctx.change.shenpiPower && au.aid === ctx.session.sessionUser.accountId ? cl.spamount : (audit_amount[index] ? parseFloat(audit_amount[index]) : null);
  4212. }
  4213. }
  4214. // 取所有工料表
  4215. responseData.data = changeList;
  4216. break;
  4217. // case 'update_tp':
  4218. // await ctx.service.changePlan.saveInfo(ctx.change.id, { name: 'total_price', val: data.updateData });
  4219. // break;
  4220. default: throw '参数有误';
  4221. }
  4222. ctx.body = responseData;
  4223. } catch (err) {
  4224. this.log(err);
  4225. ctx.body = { err: 1, msg: err.toString(), data: null };
  4226. }
  4227. }
  4228. /**
  4229. * 撤回审批
  4230. * @param ctx
  4231. * @return {Promise<void>}
  4232. */
  4233. async checkPlanAuditCancel(ctx) {
  4234. try {
  4235. if (!ctx.change.cancancel) throw '您无权进行该操作';
  4236. await ctx.service.changePlanAudit.checkCancel(ctx.change);
  4237. ctx.body = { err: 0, url: ctx.request.header.referer, msg: '' };
  4238. } catch (err) {
  4239. this.log(err);
  4240. ctx.body = { err: 1, msg: err };
  4241. }
  4242. }
  4243. /**
  4244. * 变更申请重新审批
  4245. * @param {Object} ctx - egg全局变量
  4246. * @return {void}
  4247. */
  4248. async checkPlanAgain(ctx) {
  4249. try {
  4250. // 获取终审
  4251. // const auditInfo = await this.ctx.service.changePlanAudit.getAuditorByStatus(ctx.change.id, audit.changePlan.status.checked);
  4252. if (ctx.change.status !== audit.changePlan.status.checked) {
  4253. throw '您无权进行该操作';
  4254. }
  4255. // 判断是否被变更申请调用了,是则无法发起修订
  4256. const projectInfo = await ctx.service.change.getDataByCondition({ tid: ctx.tender.id, plan_code: ctx.change.code });
  4257. if (projectInfo) {
  4258. throw '该变更方案已被变更令调用,无法发起重新审批';
  4259. }
  4260. if (ctx.session.sessionUser.loginStatus === 0) {
  4261. const code = ctx.request.body.code;
  4262. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  4263. if (!pa.auth_mobile) {
  4264. throw '未绑定手机号';
  4265. }
  4266. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  4267. const cacheCode = await app.redis.get(cacheKey);
  4268. // console.log(cacheCode);
  4269. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  4270. throw '验证码不正确!';
  4271. }
  4272. }
  4273. if ((ctx.change.finalAuditorIds.indexOf(ctx.session.sessionUser.accountId) >= 0) && ctx.change.status === audit.changePlan.status.checked) {
  4274. // 重新审批
  4275. const result = await ctx.service.changePlanAudit.checkAgain(ctx.change);
  4276. if (!result) {
  4277. throw '重新审批失败';
  4278. }
  4279. } else {
  4280. throw '您无权进行该操作';
  4281. }
  4282. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  4283. ctx.body = {
  4284. err: 0,
  4285. url: ctx.request.header.referer,
  4286. msg: '',
  4287. };
  4288. } catch (err) {
  4289. console.log(err);
  4290. // ctx.redirect(ctx.request.header.referer);
  4291. ctx.body = {
  4292. err: 1,
  4293. // url: ctx.request.header.referer,
  4294. msg: err,
  4295. };
  4296. }
  4297. }
  4298. /**
  4299. * 变更申请修订重新上报
  4300. * @param {Object} ctx - egg全局变量
  4301. * @return {void}
  4302. */
  4303. async checkPlanRevise(ctx) {
  4304. try {
  4305. if (ctx.change.status !== audit.changePlan.status.checked || ctx.session.sessionUser.accountId !== ctx.change.uid) {
  4306. throw '您无权进行该操作';
  4307. }
  4308. // 判断是否被变更申请调用了,是则无法发起修订
  4309. const projectInfo = await ctx.service.change.getDataByCondition({ tid: ctx.tender.id, plan_code: ctx.change.code });
  4310. if (projectInfo) {
  4311. throw '该变更方案已被变更令调用,无法发起修订';
  4312. }
  4313. if (ctx.session.sessionUser.loginStatus === 0) {
  4314. const code = ctx.request.body.code;
  4315. const pa = await ctx.service.projectAccount.getDataById(ctx.session.sessionUser.accountId);
  4316. if (!pa.auth_mobile) {
  4317. throw '未绑定手机号';
  4318. }
  4319. const cacheKey = 'smsCode:' + ctx.session.sessionUser.accountId;
  4320. const cacheCode = await app.redis.get(cacheKey);
  4321. // console.log(cacheCode);
  4322. if (cacheCode === null || code === undefined || cacheCode !== (code + pa.auth_mobile)) {
  4323. throw '验证码不正确!';
  4324. }
  4325. }
  4326. // 重新审批
  4327. const result = await ctx.service.changePlanAudit.checkRevise(ctx.change);
  4328. if (!result) {
  4329. throw '修订发起失败';
  4330. }
  4331. // ctx.redirect('/tender/' + changeData.tid + '/change/' + changeData.cid + '/info');
  4332. ctx.body = {
  4333. err: 0,
  4334. url: ctx.request.header.referer,
  4335. msg: '',
  4336. };
  4337. } catch (err) {
  4338. console.log(err);
  4339. // ctx.redirect(ctx.request.header.referer);
  4340. ctx.body = {
  4341. err: 1,
  4342. // url: ctx.request.header.referer,
  4343. msg: err,
  4344. };
  4345. }
  4346. }
  4347. /**
  4348. * 变更令撤销修订
  4349. * @param {Object} ctx - egg全局变量
  4350. * @return {void}
  4351. */
  4352. async cancelPlanRevise(ctx) {
  4353. try {
  4354. if (!(ctx.change.status === audit.changePlan.status.revise && (ctx.session.sessionUser.accountId === ctx.change.uid || ctx.session.sessionUser.accountId === ctx.session.sessionUser.is_admin))) {
  4355. throw '您无权进行该操作';
  4356. }
  4357. // 重新审批
  4358. const result = await ctx.service.changePlanAudit.cancelRevise(ctx.change);
  4359. if (!result) {
  4360. throw '撤销修订失败';
  4361. }
  4362. ctx.body = {
  4363. err: 0,
  4364. url: ctx.request.header.referer,
  4365. msg: '',
  4366. };
  4367. } catch (err) {
  4368. console.log(err);
  4369. ctx.body = {
  4370. err: 1,
  4371. msg: err,
  4372. };
  4373. }
  4374. }
  4375. }
  4376. return ChangeController;
  4377. };