change_controller.js 226 KB

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